有没有办法在一个处理中同时收集流的匹配元素和不匹配元素?举这个例子:
final List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
final List<Integer> even = numbers.stream().filter( n -> n % 2 == 0 ).collect( Collectors.toList() );
final List<Integer> odd = numbers.stream().filter( n -> n % 2 != 0 ).collect( Collectors.toList() );
有没有办法避免在数字列表中运行两次?类似于“匹配的收集器和不匹配的收集器”?
你可以这样做,
final Map<Boolean, List<Integer>> parityMap = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
final List<Integer> even = parityMap.get(true);
final List<Integer> odd = parityMap.get(false);
如果您有超过2个组(而不是这里使用%2的奇数和偶数),例如对余数类%3中的int进行分组,您可以使用函数:
Function<Integer, Integer> fun = i -> i%3;
List<Integer> a = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Map<Integer, List<Integer>> collect = a.stream().collect(Collectors.groupingBy(fun));
System.out.println(collect);
//{0=[3, 6, 9], 1=[1, 4, 7, 10], 2=[2, 5, 8]}
或者假设您有一个字符串列表,您想通过启动char而不是分组匹配和不匹配(例如以a或not开头)来对其进行分组,您可以执行以下操作:
Function<String, Character> fun = s -> s.charAt(0);
List<String> a = Arrays.asList("baz","buzz","azz","ayy","foo","doo");
Map<Character, List<String>> collect = a.stream().collect(Collectors.groupingBy(fun));
System.out.println(collect);
//{a=[azz, ayy], b=[baz, buzz], d=[doo], f=[foo]}