1、分组
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
排序
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
2List转Map
// 常用方式
Map<String, String> map = accounts.stream()
.collect(Collectors.toMap(Account::getId, Account::getUsername));
// 收集成实体本身map
Map<Long, Account> map = accounts.stream()
.collect(Collectors.toMap(Account::getId, account -> account));
// account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法代替,使整个方法更简洁优雅:
Map<Long, Account> map = accounts.stream()
.collect(Collectors.toMap(Account::getId, Function.identity()));
/** 上面的实现如果id有重复情况会报错(java.lang.IllegalStateException: Duplicate key)。
* toMap有个重载方法,可以传入一个合并的函数来解决key冲突问题:(如果有重复的key,则保留key1,舍弃key2)
*/
Map<Long, Account> map = accounts.stream()
.collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
map转list List<String> keylist =new ArrayList<>(map.keySet());
for(String key:keylist ){
System.out.println(key);
3过滤Filter
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
4将集合中的数据按照某个属性求和:
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
4去重
// 根据id去重
List<Person> unique = appleList.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
5列表转数组
// 列表转数组 String[] ss = listStrings.stream().toArray(String[]::new);
// 数组转列表
String[] arrays = new String[]{"a", "b", "c"};
List<String> listStrings = Stream.of(arrays).collector(Collectors.toList()) // toSet()
6list取单个值
List<String> list = goodsImageList.stream().map(goodsImage -> goodsImage.getGoodsImage()).collect(Collectors.toList());
本文介绍了如何使用Java8的Stream API进行高效的数据操作,包括List的分组、排序、转换为Map、过滤、求和、去重以及数组与List之间的转换。举例说明了各种操作的实现,如按属性分组、List转Map时处理重复键的策略,以及如何进行过滤和去重操作。
1万+

被折叠的 条评论
为什么被折叠?



