Library method to partition a collection by a predicate

前端 未结 6 670
小鲜肉
小鲜肉 2020-12-29 21:02

I have a collection of objects that I would like to partition into two collections, one of which passes a predicate and one of which fails a predicate. I was hoping there wo

6条回答
  •  长发绾君心
    2020-12-29 21:41

    seems like a good job for the new Java 12 Collectors::teeing

    var dividedStrings = Stream.of("foo", "hello", "bar", "world")
                .collect(Collectors.teeing(
                        Collectors.filtering(s -> s.length() <= 3, Collectors.toList()),
                        Collectors.filtering(s -> s.length() > 3, Collectors.toList()),
                        List::of
                ));
    System.out.println(dividedStrings.get(0)); //[foo, bar]
    System.out.println(dividedStrings.get(1)); //[hello, world]
    

提交回复
热议问题