Library method to partition a collection by a predicate

前端 未结 6 678
小鲜肉
小鲜肉 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:39

    With the new java 8 features(stream and lambda epressions), you could write:

    List words = Arrays.asList("foo", "bar", "hello", "world");
    
    Map> partitionedMap =
            words.stream().collect(
                    Collectors.partitioningBy(word -> word.length() > 3));
    
    System.out.println(partitionedMap);
    

提交回复
热议问题