Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create multiple List with lambda expression?

I have a User with age property. And in my method I have List. How can I split it to multiple List for another user like:

List<User> lt6Users = new ArrayList<User>();
List<User> gt6Users = new ArrayList<User>();
for(User user:users){
   if(user.getAge()<6){
      lt6Users.add(user);
   }
   if(user.getAge()>6){
      gt6Users.add(user);
   }
   // more condition
}

I just known 2 way with lambda expression:

lt6Users = users.stream().filter(user->user.getAge()<6).collect(Collectors.toList());
gt6Users = users.stream().filter(user->user.getAge()>6).collect(Collectors.toList());

The code above is very poor for performance because it will loop through the list many time

users.stream().foreach(user->{
  if(user.getAge()<6){
     lt6Users.add(user);
  }
  if(user.getAge()>6{
     gt6Users.add(user);
  }
});

the code above is look like the code from start code without lambda expression. Is there another way to write code using lambda expression feature like filter and Predicate?

like image 956
gianglaodai Avatar asked Dec 07 '25 10:12

gianglaodai


1 Answers

You can use Collectors.partitioningBy(Predicate<? super T> predicate) :

Map<Boolean, List<User>> partition = users.stream()
                                          .collect(Collectors.partitioningBy(user->user.getAge()<6));

partition.get(true) will give you the list of Users with ages < 6, and partition.get(false) will give you the list of the Users with ages >= 6.

like image 144
Eran Avatar answered Dec 10 '25 09:12

Eran