简体   繁体   English

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

[英]How to partition a list by predicate using java8?

I have a list a which i want to split to few small lists. 我有一个列表a我想要拆分到几个小名单。

say all the items that contains with "aaa", all that contains with "bbb" and some more predicates. 说出包含“aaa”的所有项目,包含“bbb”和更多谓词的所有内容。

How can I do so using java8? 我怎么能用java8这样做?

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);
}

I saw this post , but it was very old, before java 8. 我看过这篇文章 ,但它在Java 8之前很老了。

Like it was explained in @RealSkeptic comment Predicate can return only two results: true and false. 就像在@RealSkeptic 评论中解释的那样, Predicate只能返回两个结果:true和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. 您需要的是某种Function ,它允许您确定应该组合在一起的元素的一些常见结果。 In your case such result could be first character in its lowercase (assuming that all strings are not empty - have at least one character). 在你的情况下,这样的结果可能是小写的第一个字符(假设所有字符串都不是空的 - 至少有一个字符)。

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). 现在使用Collectors.groupingBy(function)您可以将所有元素分组到单独的列表中,并将它们存储在Map中,其中key将是用于分组的常用结果(如第一个字符)。

So your code can look like 所以你的代码看起来像

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);

Output: 输出:

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

You can use Collectors.groupingBy to turn your stream of (grouping) -> (list of things in that grouping). 您可以使用Collectors.groupingBy来转换(分组) - >(该分组中的事物列表)。 If you don't care about the groupings themselves, then call values() on that map to get a Collection<List<String>> of your partitions. 如果您不关心分组本身,则调用该映射上的values()以获取分区的Collection<List<String>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM