1. List按某个属性排序
-
需求:有个【List<RepayPlanItem> list】,需要按照【RepayPlanItem类】的某个属性【比如repayDate还款日】对list进行排序
List<RepayPlanItem> list = new ArrayList<>(......);
//1. 正序排列
list.stream()
.sorted(Comparator.comparing(RepayPlanItem::getRepayDate)) //排序
.collect(Collectors.toList()); //转list
//2.1 倒序排列,写法1
list.stream()
.sorted(Comparator.comparing(RepayPlanItem::getRepayDate).reversed()) //排序
.collect(Collectors.toList()); //转list
//2.2 倒序排列,写法2,匿名表达式写法
list.stream()
.sorted(Comparator.comparing((RepayPlanItem p) -> p.getRepayDate()).reversed()) //这里不能写成 p -> p.getRepayDate(),必须写成 (RepayPlanItem p) -> p.getRepayDate()
.collect(Collectors.toList()); //转list
2. stream流求和
-
需求:对List<T>中所有元素的某个属性求sum
// BigDecimal类
BigDecimal bb =list.stream().map(Plan::getAmount).reduce(BigDecimal.ZERO,BigDecimal::add);
//int, double, long
double max = list.stream().mapToDouble(User::getHeight).sum();
//自定义类
list.stream().map( item->item.getNeedRepay().get()).reduce(Money.zero(),Money::add);
3. 对list进行合并(一个或多个List),按照一定规则
-
需求:有个Person类,包含name和age属性。现在有List<Person> list1和List<Person> list2,要求把名字相同的归在一起,并对年龄相加
//eg1.
List<Person> list1 ={ {jack,2},{peter,2},{mary,3} }
List<Person> list2 ={ {jack,3},{peter,10},{james,1} }
要求合并为
Map<name, List<Person>> = {{jack, 5}, {peter, 12}, {mary, 3}, {james, 1}}
//实现
List<Person> list = list1.addAll(list2);
list.stream()
.collect(Collectors.toMap(Person::getName, person -> person, (p1, p2) -> { //分别表示key=getName, value=Person, 合并规则
o1.setAge(o1.getAge() + o2.getAge());
return o1;
})).values().stream().collect(Collectors.toList());
4. list分组
-
需求:有个User类,包含多个属性。现在有List<User> list,要求按照一定规则进行groupBy
-
1. 按照每个人的edu属性进行分组,返回Map<edu, List<User>>
Map <String,List < User >> collect = users.stream().collect(Collectors.groupingBy(User: :getEdu));
-
2. 按照每个人的edu属性进行分组,value为每个人的id,返回Map<edu, List<id>>
Map <String,List <Integer>> collect = users.stream().collect(Collectors.groupingBy(User: :getEdu,
//第二个参数对Map的value进行处理(映射)
Collectors.mapping(User: :getId, Collectors.toList())));
-
3. 按照每个人的edu属性进行分组,value为这个edu组内的年龄和,返回Map<edu, sumAge>
//1. 方法1
Map<String, Long> collect = users.stream().collect(Collectors.groupingBy(User: :getEdu, Collectors.counting()));
//2. 方法2
Map<String, Long> collect = users.stream().collect(Collectors.groupingBy(User: :getEdu, Collectors.counting()));
-
4. 不仅需要分组,同时也需要对Edu进行排序,TreeMap来实现
Map <String,Double > collect = users.stream().collect(Collectors.groupingBy(User: :getEdu, TreeMap::new, Collectors.summingDouble(User: :getPrice)));
-
5. 先分组,再取value的第一个元素,返回Map<edu, User>
users.stream().collect(Collectors.groupingBy(User: :getEdu, Collectors.collectingAndThen(Collectors.toList(),value->value.get(0))));
5. Map更改value,生成新的Map
-
Map<Integer, Student> 转换成 Map<Integer, StudentId>
Map<Integer, Student> map = new HashMap<>();
Map<Integer, StudentId> map1 = map.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> entry.getValue().getId()));