[英]How to process object failed to satisfy the filter in java 8 stream
I am trying to process object which is failed to satisfy the filter condition in the stream. 我正在尝试处理无法满足流中的过滤条件的对象。
List<Integer> list = Arrays.asList(1,23,43,12,4,5);
list.stream().filter( i -> i > 10).collect(Collections.toList);
This will return a list of Object greater than 10. but I also want to process the objects which are unable to satisfy the condition (>10). 这将返回大于10的Object列表。但我还想处理无法满足条件的对象(> 10)。
Thank You. 谢谢。
Map<Boolean, List<Integer>> map = list.stream()
.collect(Collectors.partitioningBy(i > 10));
map.get(false/true).... do whatever you want with those that failed or not
I would just run two sweeps with stream()
to get two different lists: 我将使用stream()
运行两次扫描以获得两个不同的列表:
List<Integer> list = Arrays.asList(1,23,43,12,4,5);
List<Integer> largerThanTen = list.stream().filter( i -> i > 10)
.collect(Collectors.toList());
List<Integer> smallerOrEqualToTen = list.stream().filter( i -> i <= 10)
.collect(Collectors.toList());
I think this is more readable than trying to do it in a one-liner, resulting in a less-idiomatic data structure. 我认为这比尝试在单行中执行更具可读性,从而导致较少惯用的数据结构。
List<Integer> list = Arrays.asList(1,23,43,12,4,5);
list.stream().filter( i -> i > 10).collect(Collections.toList);
change to 改成
Map < Boolean, List < Integer > > map = Stream.of( 1, 23, 43, 12, 4, 5 ).collect( Collectors.groupingBy( e -> e > 10 ) );
then you can use : 然后你可以使用 :
map.get( false )// is list of has not condition
map.get(true) // is list of has condition
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.