库方法通过谓词分割集合 [英] Library method to partition a collection by a predicate

查看:138
本文介绍了库方法通过谓词分割集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象集合,我想分区成两个集合,其中一个传递一个谓词,其中一个失败的谓词。我希望有一个 Guava 方法来做到这一点,但他们最近的方法是过滤器,它不给我其他集合。

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 would be a Guava method to do this, but the closest they come is filter, which doesn't give me the other collection.

我会形象的方法的签名将是这样: p>

I would image the signature of the method would be something like this:

public static <E> Pair<Collection<E>, Collection<E>> partition(Collection<E> source, Predicate<? super E> predicate)

快速代码自己,但我正在寻找一个现有的库方法,做我想要的。

I realize this is super fast to code myself, but I'm looking for an existing library method that does what I want.

推荐答案

使用Guava的 Multimaps.index

Use Guava's Multimaps.index.

的单词分为两部分:长度大于3的那些和不大于3的那些。

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

List<String> words = Arrays.asList("foo", "bar", "hello", "world");

ImmutableListMultimap<Boolean, String> partitionedMap = Multimaps.index(words, new Function<String, Boolean>(){
    @Override
    public Boolean apply(String input) {
        return input.length() > 3;
    }
});
System.out.println(partitionedMap);

列印:

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

这篇关于库方法通过谓词分割集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆