如何使用lambda表达式创建多个List?

gia*_*dai 3 lambda predicate filter java-8 java-stream

我有一个年龄属性的用户.在我的方法中,我有List.如何将其拆分为多个List,以供其他用户使用:

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
}
Run Code Online (Sandbox Code Playgroud)

我只知道lambda表达式的2种方式:

lt6Users = users.stream().filter(user->user.getAge()<6).collect(Collectors.toList());
gt6Users = users.stream().filter(user->user.getAge()>6).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

上面的代码性能很差,因为它会在很多时候循环遍历列表

users.stream().foreach(user->{
  if(user.getAge()<6){
     lt6Users.add(user);
  }
  if(user.getAge()>6{
     gt6Users.add(user);
  }
});
Run Code Online (Sandbox Code Playgroud)

上面的代码看起来像没有lambda表达式的起始代码中的代码.有没有其他方法使用像filter和Predicate这样的lambda表达式函数编写代码?

Era*_*ran 5

你可以使用Collectors.partitioningBy(Predicate<? super T> predicate):

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

partition.get(true)将为您提供年龄<6的用户列表,并partition.get(false)为您提供年龄> = 6的用户列表.

  • @gianglaodai`partitioningBy`仅适用于通过单个谓词将List分为两个分区。您可以使用“ Collectors.groupingBy”将列表分成年龄完全相同的用户组(即,您将获得“ Map &lt;Integer,List &lt;User &gt;&gt;”,但这也许并不是您想要的。 (2认同)