class User(){ private String userCode; private String userName; } List<User> userList; //list 集合提取字段数组 String [] productCodes = userList.stream().map(User::getUserCode).toArray(String[]::new); //list 集合提取某个字段 转换为新的list List<String> userCodes = userList.stream().map(user->user.getUserCode()).collect(Collectors.toList()); //list 按照字段分组 依据字段等值的 放在同一个集合并指向KEY Map<String, List<User>> userListMap = userList.stream().collect(Collectors.groupingBy(User::getUserCode)); //list过滤筛选集合 List<User> userList = userList .stream().filter(er -> er.getUserName().equals("张三")).collect(Collectors.toList()); // 根据字段过滤去重 List<String> rs = new ArrayList<>(); List<User> checkUserList = userList.stream().filter( v -> { boolean flag = !rs.contains(v.getUserName()); rs.add(v.getUserName()); return flag; }).collect(Collectors.toList());
//list集合排序 List<SysMenuEntity> sysMenus; //第一种升序 sysMenus.sort((o1, o2) -> o1.getSort().compareTo(o2.getSort()));
//第一种 降序
sysMenus.sort((o1, o2) -> o2.getSort().compareTo(o1.getSort()));
//第二种 Collections.sort(sysMenus,(s1,s2) -> s1.getSort().compareTo(s2.getSort()));
// 需要筛选的条件:从stuList中筛选出年龄为21和22的学生 List<Integer> ageList = new ArrayList<Integer>(); ageList.add(21); ageList.add(22); // JDK1.8提供了lambda表达式, 可以从stuList中过滤出符合条件的结果。 // 定义结果集 List<Student> result = null; result = stuList.stream() .filter((Student s) -> ageList.contains(s.getAge())) .collect(Collectors.toList());
//取最大值 Optional<Student> userOp= result.stream(). max(Comparator.comparingInt(Student ::getAge)); Student maxDay = userOp.get();
求和
BigDecimal:
BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
int、double、long:
double max = list.stream().mapToDouble(User::getHeight).sum();
二。
BigDecimal bb =list.stream().map(User::getAmount).reduce(BigDecimal.ZERO,(a,b)->{
if (a == null || b == null) {
//报错或定义兜底的值
// throw new Exception("");
return BigDecimal.ZERO;
}
return a.add(b);
});
三。
int ageSum = userList.stream().mapToInt(User::getAge).sum();
拓展工具
//拓展工具 list转map public static <K,V> Map<K,V> listToMap(List<V> list, String keyField){ Map<K,V> result = new HashMap<>(); if(list != null && list.size() > 0 && StringUtils.isNotEmpty(keyField)){ String firstLetter = keyField.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + keyField.substring(1); try { for(Object obj : list){ Method method = obj.getClass().getMethod(getter,null); K key = (K) method.invoke(obj,null); if(key != null && StringUtils.isNotEmpty(key.toString())){ result.put(key,(V) obj); } } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } return result; }