如何使用 java8 通过谓词对列表进行分区?

How to partition a list by predicate using java8?(如何使用 java8 通过谓词对列表进行分区?)

本文介绍了如何使用 java8 通过谓词对列表进行分区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表 a 我想将其拆分为几个小列表.

I have a list a which i want to split to few small lists.

说出所有包含aaa"的项目,所有包含bbb"和一些谓词的项目.

say all the items that contains with "aaa", all that contains with "bbb" and some more predicates.

如何使用 java8 做到这一点?

How can I do so using java8?

我看到了这个 post,但它只分成 2 个列表.

I saw this post but it only splits to 2 lists.

public void partition_list_java8() {

    Predicate<String> startWithS = p -> p.toLowerCase().startsWith("s");

    Map<Boolean, List<String>> decisionsByS = playerDecisions.stream()
            .collect(Collectors.partitioningBy(startWithS));

    logger.info(decisionsByS);

    assertTrue(decisionsByS.get(Boolean.TRUE).size() == 3);
}

我看到了这个帖子,但在 java 8 之前它已经很老了.

I saw this post, but it was very old, before java 8.

推荐答案

就像在 @RealSkeptic 中解释的那样 评论 谓词 只能返回两个结果:真和假.这意味着您只能将数据分成两组.
您需要的是某种 Function ,它可以让您确定应该组合在一起的元素的一些常见结果.在您的情况下,这样的结果可能是小写的第一个字符(假设所有字符串都不为空 - 至少有一个字符).

Like it was explained in @RealSkeptic comment Predicate can return only two results: true and false. This means you would be able to split your data only in two groups.
What you need is some kind of Function which will allow you to determine some common result for elements which should be grouped together. In your case such result could be first character in its lowercase (assuming that all strings are not empty - have at least one character).

现在使用 Collectors.groupingBy(function) 您可以将所有元素分组到单独的列表中并将它们存储在 Map 中,其中键将是用于分组的常见结果(如第一个字符).

Now with Collectors.groupingBy(function) you can group all elements in separate Lists and store them in Map where key will be common result used for grouping (like first character).

所以你的代码看起来像

Function<String, Character> firstChar =  s -> Character.toLowerCase(s.charAt(0));

List<String> a = Arrays.asList("foo", "Abc", "bar", "baz", "aBc");
Map<Character, List<String>> collect = a.stream()
        .collect(Collectors.groupingBy(firstChar));

System.out.println(collect);

输出:

{a=[Abc, aBc], b=[bar, baz], f=[foo]}

这篇关于如何使用 java8 通过谓词对列表进行分区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何使用 java8 通过谓词对列表进行分区?

基础教程推荐