Reputation: 321
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?
Upvotes: 3
Views: 2210
Reputation: 321
I've found a way to use lambda expression for this problem: Write a method with Predicate:
public void addUser(List<User> users,User user,Predicate<User> p){
if(p.test(user)){
users.add(user);
}
}
So the loop can be write like this:
users.foreach(user->{
addUser(lt6Users,user,(User u)->u.getAge()<6);
addUser(gt6Users,user,(User u)->u.getAge()>6);
// more condition
});
Upvotes: -1
Reputation: 393781
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.
Upvotes: 6