Elad Benda Elad Benda - 1 year ago 99
Java Question

who to partition a list by predicate using java8?

I have a list

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


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

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

Answer Source

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



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