Java8 list集合过滤/分组/排序/去重/求和/根据字段获取列等处理方式

list集合常用处理:

  1. list过滤
//示例1 注意number是默认final的,赋值后不能在变
 List teamRoundEntities = teamRoundEntityList.stream().filter(teamEntity -> teamEntity.getRound() == number).collect(Collectors.toList());
  1. list分组
//示例1
Map> roundListMap = rulesNameVoList.stream().collect(Collectors.groupingBy(RulesNameVo::getNumber));
  1. list排序
//示例1:从小到大,正序排序

List collect = rulesNameVoList.stream().sorted(Comparator.comparing(RulesNameVo::getNumber)).collect(Collectors.toList());
//示例2:倒序
List collect = rulesNameVoList.stream().sorted(Comparator.comparing(RulesNameVo::getNumber).reversed()).collect(Collectors.toList());
  1. list获取某字段集合
//示例1
List collect = rulesEntityList.stream().map(RulesEntity::getId).collect(Collectors.toList());
  1. list求和
//示例 mapToLong / mapToInt /mapToDouble 用法一样
long sum = teamRoundEntityList.stream().mapToLong(TeamRoundEntity::getNumber).sum();
  1. list去重
//示例1 根据某字段去重
 List teamRoundList = teamRoundEntityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TeamRoundEntity::getTeamId))), ArrayList::new));
 //示例2 整个对象去重(主要用于单数据类型集合)
 List teamRoundList = teamRoundEntityList.stream().distinct().collect(Collectors.toList());
List myList = list.stream().distinct().collect(Collectors.toList());
  1. list获取最大最小行数据
//示例1 获取最大
TeamRoundEntity teamRoundEntity = teamRoundEntityList.stream().max(Comparator.comparing(TeamRoundEntity::getNumber)).get();

//示例2获取最小
TeamRoundEntity teamRoundEntity = teamRoundEntityList.stream().min(Comparator.comparing(TeamRoundEntity::getNumber)).get();

你可能感兴趣的:(list,java,数据结构)