List过滤的三种方式:
- 通过java8中filter过滤器进行过滤
- 通过For循环遍历过滤
- 通过ForEach遍历过滤
public class FilteringList { /** * 通过java8中filter过滤器进行过滤 * @param userList * @return */ public List<User> filterByStream(List<User> userList){ return userList.stream() .filter(user -> Objects.nonNull(user)) .filter(user -> user.getAge()>=12) .collect(Collectors.toList()); } /** * 通过For循环遍历过滤 * @param userList * @return */ public List<User> filterByFor(List<User> userList){ List<User> newUserList = new ArrayList<>(); for (User user : userList) { if(user != null && user.getAge()>=12){ newUserList.add(user); } } return newUserList; } /** * 通过ForEach遍历过滤 * @param userList * @return */ public List<User> filterByForEach(List<User> userList){ List<User> newUserList = new ArrayList<>(); userList.forEach(user -> { if(user != null && user.getAge()>=12){ newUserList.add(user); } }); return newUserList; } }
标签:JAVA,List,return,userList,过滤,user,newUserList From: https://www.cnblogs.com/Fooo/p/17846215.html