Library method to partition a collection by a predicate

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

    Use Guava's Multimaps.index.

    Here is an example, which partitions a list of words into two parts: those which have length > 3 and those that don't.

    List words = Arrays.asList("foo", "bar", "hello", "world");
    
    ImmutableListMultimap partitionedMap = Multimaps.index(words, new Function(){
        @Override
        public Boolean apply(String input) {
            return input.length() > 3;
        }
    });
    System.out.println(partitionedMap);
    

    prints:

    false=[foo, bar], true=[hello, world]
    

提交回复
热议问题