How to partition a list by predicate using java8?

前端 未结 2 1083
情话喂你
情话喂你 2020-12-16 10:34

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

say all the items that contains with \"aaa\", all that contains with \"bbb\" and some more pre

相关标签:
2条回答
  • 2020-12-16 11:08

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

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

    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]}
    
    0 讨论(0)
  • 2020-12-16 11:24

    You can use Collectors.groupingBy to turn your stream of (grouping) -> (list of things in that grouping). If you don't care about the groupings themselves, then call values() on that map to get a Collection<List<String>> of your partitions.

    0 讨论(0)
提交回复
热议问题