stream方法API
list转map
-
list泛型对象的任意一属性进行分组,构成Map<属性,Object>
Map<String,List<User>> map= userList.stream().collect(Collectors.groupingBy(User::getName));
-
list泛型对象的任意两个属性构成Map<属性1, 属性2>
public Map<Long, String> getIdNameMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername)); }
-
list泛型对象的任意一属性为key,泛型对象为value构成Map<属性,Object>
// 方式一:account -> account是一个返回自己本身的lambda表达式 public Map<Long, Account> getIdAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId,account -> account)); // 方式二:其实还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅 public Map<Long, Account> getIdAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity())); } // 方式是三:name重复的,方式二就会抛出异常(java.lang.IllegalStateException: Duplicate key),可使用重载方法传入一个合并相同key的函数来解决key冲突问题: public Map<String, Account> getNameAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2)); }
-
指定返回Map的具体实现数据结构
// 指定一个Map的具体实现,如:LinkedHashMap public Map<String, Account> getNameAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new)); }
list转list
-
list泛型对象转为另一个对象的list
List<SettlementInfoPO> settlementInfoPOS = timeoutData.stream().map(item -> { SettlementInfoPO settlementInfoPO = item.convertPo(); return settlementInfoPO; }).collect(Collectors.toList());
-
list泛型对象的某个属性构成另一个list
roomList.stream().map(Room::getAvgPrice).collect(Collectors.toList());
-
list泛型对象的某属性排序后构成另一个list
// 升序 roomList.stream().sorted(Comparator.comparing(Room::getAvgPrice)).collect(Collectors.toList()); // 降序 roomList.stream().sorted(Comparator.comparing(Room::getAvgPrice).reversed()).collect(Collectors.toList()); list.sort((a, b) -> a.name.compareTo(b.name));
-
去重,需要重写对象的equals和hashcode方法
roomList.stream().distinct().collect(Collectors.toList());
-
list泛型对象的某些属性过滤后构成另一个list
// 且 roomList.stream().filter(benefit -> benefit.getId() == 1 && benefit.getAge() == 20).collect(Collectors.toList()); // 或 roomList.stream().filter(benefit -> benefit.getId() == 1 || benefit.getId() == 20).collect(Collectors.toList());
-
返回list第一个元素
// 返回第一个元素,没有返回null roomList.stream().findFirst().orElse(null);