下面来介绍下java流的使用,希望能帮助到大家。
流程:
原集合 —> 流 —> 各种操作(如:过滤、分组、统计、排序等等...) —> 终端操作
流分为两种:一种是串行流stream(); 和并行流parallelStream();
降序
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge).reversed()).collect(Collectors.toList());
升序
List<StudentInfo> studentsSortName = studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList());
根据 List 中 Object 某个属性去重
List<BlogHistory> filterList = list.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(BlogHistory::getArticleId))), ArrayList::new));
去重单个属性,String类型
List<String> memberSearchHistoryList = memberSearchHistories.stream().map(MemberSearchHistory::getKeyWord).distinct().collect(Collectors.toList());
返回数据格式如下:
{
"msg": "操作成功",
"code": 200,
"data": [
"坡头",
"安详",
"更为",
"和任务给",
"官网",
"个问题我",
"发斯蒂芬"
]
}
根据List 中 Object 多个属性去重
List<BlogHistory> filterList1 =list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getArticleId() + ";" + o.getMemberId()))), ArrayList::new));
查询多少条
List<MemberSearchHistory> limitList = filterList.stream().limit(8).collect(toList());
计算某个属性的总和
long count = ordersList.stream().sorted(Comparator.comparing(Orders::getOrderNo)).collect(Collectors.counting());
Integer totalAge = list.stream().collect(Collectors.summingInt(Users::getAge));
计算总金额,类型(BigDecimal)
BigDecimal sum = list.stream() .map(Users::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
计算总数据总和
Long count = list.stream().collect(Collectors.counting());
查找某一属性最大值
最小 使用(minBy)
Optional<Users> max = list.stream().collect(Collectors.maxBy(Comparator.comparing(Users::getAge)));
查list集合中抽取多个id [1,2,3,4,5]
List<Long> shopIds = shopInfoList.stream().map(o -> o.getShopId()).collect(Collectors.toList());
统计个城市的用户个数有多少
Map<String, Long> cityCountMap = list.stream().collect(Collectors.groupingBy(Users::getAddress,Collectors.counting()));