使用番石榴库从数组列表中获取非过滤项

Getting Non Filtered Item from array list using Guava Library

我可以使用波纹管函数根据我的过滤条件获取所有项目,但我还需要未过滤的项目列表,我的意思是说 isGroup 为真的项目我可以轻松获得但无法获得isGroup 为 true 的项目,我不想为同一任务使用另一个过滤器,是否有任何内置函数?

  final Collection nonGroupItems= Collections2.filter(rosterList, new Predicate<Roster>() {
            @Override
            public boolean apply(Roster input) {
                return  ! input.getIsGroup();
            }
        });

是的。您可以使用 Multimaps.index(Iterable, Function) 到 index/group/partition 通过某个键(在本例中为 isGroup)您的值。然后,您将可以访问每个值列表:一个列表包含 isGroup returns true 的值,另一个列表包含 isGroup returns false.

例如:

final ImmutableListMultimap<Boolean, Roster> rostersByIsGroup = Multimaps.index(rosterList,
        new Function<Roster, Boolean>() {
            @Override
            public Boolean apply(Roster input) {
                return input.getIsGroup();
            }
        });
final ImmutableList<Roster> groupItems = rostersByIsGroup.get(true);
final ImmutableList<Roster> nonGroupItems = rostersByIsGroup.get(false);

如果您使用 Java 8:

final ImmutableListMultimap<Boolean, Roster> rostersByIsGroup = Multimaps.index(rosterList,
        Roster::getIsGroup);
final ImmutableList<Roster> groupItems = rostersByIsGroup.get(true);
final ImmutableList<Roster> nonGroupItems = rostersByIsGroup.get(false);