Partition a List into Two Lists Based on a Predicate


Situation:
You want to split a list of names into two lists: one where the name length is greater than 3 and one where it’s not.

Solution:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

Map<Boolean, List<String>> partitionedNames = names.stream()
    .collect(Collectors.partitioningBy(name -> name.length() > 3));

System.out.println(partitionedNames);

Explanation:
partitioningBy divides the stream into two groups based on the given predicate (name length greater than 3).

Result:

{false=[Bob], true=[Alice, Charlie, David]}

Discover more from Byte Code

Subscribe to get the latest posts sent to your email.

Leave a Reply

I’m A Java Enthusiast

Welcome to Byte-Code, your go-to corner of the internet for all things Java. Here, I invite you to join me on a journey through the world of programming, where we’ll explore the intricacies of Java, dive into coding challenges, and build solutions with a touch of creativity. Let’s code something amazing together!

Let’s connect