Collectors类常用方法
文章目录
- Collectors类常用方法
- 1.toList、toSet、toMap
- 2.joining、counting、summingInt、minBy
- 3.groupingBy
1.toList、toSet、toMap
Collector<T, ?, List<T>> toList();
Collector<T, ?, Set<T>> toSet();
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,Function<? super T, ? extends U> valueMapper)
List<String> strList = list.stream().map(DemoObj::getCode).collect(Collectors.toList());
Set<String> collect = list.stream().map(DemoObj::getCode).collect(Collectors.toSet());
Map<String, Integer> collect = list.stream().collect(Collectors.toMap(DemoObj::getCode, DemoObj::getAmount));
2.joining、counting、summingInt、minBy
Collector<CharSequence, ?, String> joining(CharSequence delimiter);
<T> Collector<T, ?, Long> counting();
<T> Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)
<T> Collector<T, ?, Optional<T>> minBy(Comparator<? super T> comparator)
String str = list.stream().map(DemoObj::getCode).collect(Collectors.joining(","));
Long collect = list.stream().map(DemoObj::getCode).collect(Collectors.counting());
Integer collect = list.stream().collect(Collectors.summingInt(DemoObj::getAmount));
Optional<DemoObj> collect = list.stream().collect(Collectors.minBy(Comparator.comparingInt(DemoObj::getAmount)));
3.groupingBy
<T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier);
Map<Integer, List<DemoObj>> collect = list.stream().collect(Collectors.groupingBy(DemoObj::getAmount));