Collectors详解

java8中Collectors的方法:

文章目录

 

toCollection

此函数返回一个收集器,它将输入元素累积到一个集合中。


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

// toCollection()
Collection<String> strCollection = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strCollection); // [a, b, c]

Set<String> strSet = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));
System.out.println(strSet); // [a, b, c]

List<String> strList1 = strList.parallelStream().sorted(String::compareToIgnoreCase)
		.collect(Collectors.toCollection(ArrayList::new));
System.out.println(strList1); // [a, a, b, b, c]

toList()

返回一个收集器,它将输入元素累积到一个新的List中。


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

List<String> uppercaseList = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(uppercaseList); // [A, B, C, B, A]

List<String> uppercaseUnmodifiableList = strList.parallelStream().map(String::toUpperCase)
		.collect(Collectors.toUnmodifiableList());
System.out.println(uppercaseUnmodifiableList); // [A, B, C, B, A]

  •  

toSet()


List<String> strList = Arrays.asList("a", "b", "c", "b", "a");

Set<String> uppercaseSet = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toSet());
System.out.println(uppercaseSet); // [A, B, C]

Set<String> uppercaseUnmodifiableSet = strList.parallelStream().map(String::toUpperCase)
		.collect(Collectors.toUnmodifiableSet());
System.out.println(uppercaseUnmodifiableSet); // [A, B, C]

toMap

映射生成map

Map<String, String> map = Stream.of("a", "b", "c")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase));
System.out.println(map); // {a=A, b=B, c=C}

// Duplicate Keys will throw: Exception in thread "main"
// java.lang.IllegalStateException: Duplicate key a (attempted merging values A
// and A)
Map<String, String> mapD = Stream.of("a", "b", "c", "b", "a")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat));
System.out.println(mapD); // {a=AA, b=BB, c=C}

// above are HashMap, use below to create different types of Map
TreeMap<String, String> mapTree = Stream.of("a", "b", "c", "b")
		.collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat, TreeMap::new));
System.out.println(mapTree); {a=A, b=BB, c=C}

joining

连接字符串


String concat = Stream.of("a", "b").collect(Collectors.joining());
System.out.println(concat); // ab

String csv = Stream.of("a", "b").collect(Collectors.joining(","));
System.out.println(csv); // a,b

String csv1 = Stream.of("a", "b").collect(Collectors.joining(",", "[", "]"));
System.out.println(csv1); // [a,b]

String csv2 = Stream.of("a", new StringBuilder("b"), new StringBuffer("c")).collect(Collectors.joining(","));
System.out.println(csv2); // a,b

mapping/flatMapping

它将Function应用于输入元素,然后将它们累积到给定的Collector


Set<String> setStr = Stream.of("a", "a", "b")
		.collect(Collectors.mapping(String::toUpperCase, Collectors.toSet()));
System.out.println(setStr); // [A, B]

Set<String> setStr1 = Stream.of("a", "a", "b")
		.collect(Collectors.flatMapping(s -> Stream.of(s.toUpperCase()), Collectors.toSet()));
System.out.println(setStr1); // [A, B]

filtering

设置过滤条件


List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");
Set<String> set = strList2.parallelStream()
		.collect(Collectors.filtering(s -> s.length() < 2, Collectors.toSet()));
System.out.println(set); // [1, 2]

collectingAndThen

返回一个收集器,该收集器将输入元素累积到给定的收集器中,然后执行其他完成功能

List<String> strList2 = Lists.newArrayList("1", "2", "10", "100", "20", "999");

List<String> unmodifiableList = strList2.parallelStream()
		.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
System.out.println(unmodifiableList); // [1, 2, 10, 100, 20, 999]

counting

计数


Long evenCount = Stream.of(1, 2, 3, 4, 5).filter(x -> x % 2 == 0).collect(Collectors.counting());
System.out.println(evenCount); // 2

minBy

根据给定的比较器返回最小元素


Optional<Integer> min = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> x - y));
System.out.println(min); // Optional[1]

maxBy

它根据给定的比较器返回最大元素

Optional<Integer> max = Stream.of(1, 2, 3, 4, 5).collect(Collectors.maxBy((x, y) -> x - y));
		System.out.println(max); // Optional[5]

summingInt/summingLong/summingDouble

求总和

List<String> strList3 = Arrays.asList("1", "2", "3", "4", "5");
Integer sum = strList3.parallelStream().collect(Collectors.summingInt(Integer::parseInt));
System.out.println(sum); // 15

Long sumL = Stream.of("12", "23").collect(Collectors.summingLong(Long::parseLong));
System.out.println(sumL); // 35

Double sumD = Stream.of("1e2", "2e3").collect(Collectors.summingDouble(Double::parseDouble));
System.out.println(sumD); // 2100.0

averagingInt/averagingLong/averagingDouble

求平均值

List<String> strList4 = Arrays.asList("1", "2", "3", "4", "5");
Double average = strList4.parallelStream().collect(Collectors.averagingInt(Integer::parseInt));
System.out.println(average); // 3.0

Double averageL = Stream.of("12", "23").collect(Collectors.averagingLong(Long::parseLong));
System.out.println(averageL); // 17.5

Double averageD = Stream.of("1e2", "2e3").collect(Collectors.averagingDouble(Double::parseDouble));
System.out.println(averageD); // 1050.0

groupingBy

分组

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingBy(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

groupingByConcurrent

分组,是并发和无序的

Map<Integer, List<Integer>> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.groupingByConcurrent(x -> x * 10));
System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}

partitioningBy

返回一个Collector,它根据Predicate对输入元素进行分区,并将它们组织成Map <Boolean,List >。


Map<Boolean, List<Integer>> mapPartitionBy = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(x -> x % 2 == 0));
System.out.println(mapPartitionBy); // {false=[1, 3, 5, 3], true=[2, 4, 4]}

BinaryOperator

返回一个收集器,它在指定的BinaryOperator下执行其输入元素的减少。这主要用于多级缩减,例如使用groupingBy()和partitioningBy()方法指定下游收集器


Map<Boolean, Optional<Integer>> reducing = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy(
		x -> x % 2 == 0, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Integer::intValue)))));
System.out.println(reducing); // {false=Optional[5], true=Optional[4]}

summarizingInt

返回统计数据:min, max, average, count, sum


IntSummaryStatistics summarizingInt = Stream.of("12", "23", "35")
    .collect(Collectors.summarizingInt(Integer::parseInt));
System.out.println(summarizingInt);
//IntSummaryStatistics{count=3, sum=70, min=12, average=23.333333, max=35}

相关链接:

java8中map新增方法详解
java8中Stream的使用
java8中Collection新增方法详解
java8中Collectors的方法使用实例
java8中常用函数式接口
java8中的方法引用和构造函数引用
java8中的Collectors.groupingBy用法
java8中的Optional用法
java8中的日期和时间API

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`Collectors.collectingAndThen()` 是一个非常有用的方法,它可以将一个收集器(Collector)转换为另一个收集器或者一个最终的结果。 它的方法签名如下: ```java public static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(Collector<T, A, R> downstream, Function<R, RR> finisher) ``` 其中,`downstream` 参数是需要转换的收集器,`finisher` 参数是一个函数,它将最终的结果类型 `R` 转换为另一个类型 `RR`。 `Collectors.collectingAndThen()` 方法的作用是,首先使用 `downstream` 收集器收集元素,然后将收集的结果交给 `finisher` 函数进行最终的转换,得到最终的结果 `RR`。 例如,可以将 `Collectors.toList()` 收集器转换为一个 `List` 类型的最终结果: ```java List<String> strings = Arrays.asList("a", "b", "c", "d", "e"); List<String> result = strings.stream() .collect(Collectors.collectingAndThen(Collectors.toList(), ArrayList::new)); ``` 在上面的示例中,我们将一个字符串列表转换为一个新的 `ArrayList` 对象,使用了 `Collectors.collectingAndThen()` 方法,将 `Collectors.toList()` 收集器转换为一个 `List` 类型的最终结果。 除了将收集器转换为最终结果类型之外,`Collectors.collectingAndThen()` 方法还可以将收集器转换为另一个收集器。例如,可以将一个收集器转换为一个 `Map` 类型的收集器: ```java List<String> strings = Arrays.asList("a", "bb", "ccc", "dddd", "eeeee"); Map<Integer, String> result = strings.stream() .collect(Collectors.collectingAndThen( Collectors.toMap(String::length, Function.identity()), Collections::unmodifiableMap)); ``` 在上面的示例中,我们将一个字符串列表按照长度进行分组,然后使用 `Collectors.collectingAndThen()` 方法,将 `Collectors.toMap()` 收集器转换为一个不可修改的 `Map` 类型的最终结果。这里的 `Function.identity()` 方法用于将字符串本身作为 `Map` 的值,`Collections::unmodifiableMap` 方法用于将 `Map` 包装为不可修改的形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值