Java 8中 lambda表达式、Stream API的常见用法

1、取出集合中的某个字段:

  //拿到车辆ids
List carIds = parkCarInDbList.stream().map(ParkCar::getId).collect(Collectors.toList());

2、集合直接进行遍历然后进行相关操作:

 List cars = carService.getListByCarId(carIds);
            cars.forEach(car -> {
                String plate = car.getPlate();
                parkCarPlatesInDbList.add(plate);
                parkCarPlatesIdInDbMap.put(plate, car.getParkCarId());

3、直接使用filter过滤,sum进行聚合操作:

List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
                 .filter(number -> number % 2 == 0)
                 .mapToInt(number -> number * 2)
                 .sum();
System.out.println(sum);

4、BigDecimal金额进行相加:

  //寄售订单金额
      BigDecimal consignTotalPrice = saleOrderVoList.stream()
          .map(HomeStatisticsOrderVo::getTotalPrice)
          .reduce(BigDecimal.ZERO, BigDecimal::add);

5、使用count个数相加:

  Integer consignUser = Math.toIntExact(
          saleOrderVoList.stream().map(HomeStatisticsOrderVo::getUserNumber)
              .count());

6、使用Collectors.toMap将集合转成map:

  Map areaMap = areaList.stream().collect(Collectors.toMap(BuildAreaV1::getId, BuildAreaV1::getAreaName));

7、distinct进行去重:

List buildingIds = vos.stream().map(BuildElevatorListVO::getBuildingId).distinct().collect(Collectors.toList());

8、使用Collectors.groupingBy根据某个字段进行集合分组

 Map> userMap =userList.stream().collect(Collectors.groupingBy(UserV1::getParkId));

9、使用stream().sorted()根据某个字段进行排序之倒叙:

 List collect = list.stream().sorted(Comparator.comparing(CompanyUserStatisticVO::getPersonCount).reversed()).collect(Collectors.toList());

10、使用stream().sorted()根据某个字段进行排序之正叙:

List numbers = Arrays.asList(5, 2, 1, 4, 3);
List sortedNumbers = numbers.stream()
                                     .sorted()
                                     .collect(Collectors.toList());
System.out.println(sortedNumbers);

你可能感兴趣的:(java,开发语言,java-ee)