Elad Benda Elad Benda - 7 months ago 49
Java Question

who to partition a list by predicate using java8?

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

How can I do so using 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.

Answer

You may want to group it in Map of Lists where key will be first character. For instance

List<String> a = Arrays.asList("foo", "Abc", "bar", "baz", "aBc");

Map<Character, List<String>> collect = a.stream()
        .collect(Collectors.groupingBy((String s) -> s.toLowerCase().charAt(0)));

System.out.println(collect);

Output:

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