1.根据对象集合中的对象的某个属性排序,再根据第二个属性排序
运用场景:按不同组排序,输出集合导出excel;
数据源
List<TestVO> tests = Arrays.asList(new TestVO("A","1"),new TestVO("A","4"),new TestVO("A","6"), new TestVO("C","1"), new TestVO("A","2"),new TestVO("B","2"),
new TestVO("B","1"));
List<TestVO> tests2 = tests.stream().sorted(Comparator.comparing(TestVO::getValue).thenComparing(TestVO::getType)).collect(Collectors.toList());
2.如上排序后,需要取每一个组的前几个数据
Map<String,List<TestVO>> tests3 = tests.stream().sorted(
Comparator.comparing(TestVO::getValue)
.thenComparing(TestVO::getType))
.collect(Collectors.groupingBy(TestVO::getType,LinkedHashMap::new,Collectors.toList()));
List<TestVO> result = new ArrayList<>();
tests3.forEach((v , k) ->{
result.addAll(k.stream().limit(3).collect(Collectors.toList()));
});
result.stream().forEach(System.out::print);
3.Map获取键值对的几种方式
Map<String,String> maps = new HashMap<>();
maps.put("1","苹果");
maps.put("2","菠萝");
maps.put("3","西瓜");
//0.直接获取键值内容
maps.forEach((k,v) ->{
System.out.print(k+v);
});
//1.keySet获取所有键
maps.keySet().forEach(e ->{
System.out.print(maps.get(e));
});
//或者使用迭代器遍历
if(maps.keySet() != null){
Iterator iterator = keys.iterator();
while (iterator.hasNext()){
Object key = iterator.next();
System.out.println(key);
}
}
//2.values获取所有值
maps.values().forEach(System.out::print);
//3.获取所有键值对组
// Set<Map.Entry<String, Long>> set = map.entrySet();
// for(Map.Entry entry : set){...}
maps.entrySet().forEach(e ->{
System.out.print(e.getKey() + e.getValue());
});
4.对象集合中,某两个Integer属性相加
vo.setTotal(String.valueOf(v.stream().map(RankCountVO::getRankCount).reduce(0,(v1,v2) -> v1+v2)));
5.需要根据某值设置排名且需要实现1,2,2,4,5情况
先初步排序且设置排名
List<XXVO> rankOriginal = list.stream().sorted(Comparator.<XXVO,Integer>comparing(e ->
Integer.valueOf(e.getTotal()))
.thenComparing(e -> Integer.valueOf(e.getGold()))
.thenComparing(e -> Integer.valueOf(e.getSilver()))
.thenComparing(e -> Integer.valueOf(e.getBronze())).reversed()).collect(Collectors.toList());
//设置总排名
for (int i = 0 ; i< rankOriginal.size() ; i++){
rankOriginal.get(i).setRankTotal(String.valueOf(i + 1));
}
排序后得到1 2 3 4正常排名设置,此时相同分数排名不同
//处理同数量排名的情况 如 1 2 2 4
rankOriginal.stream().sorted(Comparator.<XXVO,Integer>comparing(e -> Integer.valueOf(e.getTotal()))
.thenComparing(e -> Integer.valueOf(e.getGold()))
.thenComparing(e -> Integer.valueOf(e.getSilver()))
.thenComparing(e -> Integer.valueOf(e.getBronze()))
.thenComparing((XXVO m1 , XXVO m2) -> {
m2.setRankTotal(m1.getRankTotal());
return 0;
}).reversed()).collect(Collectors.toList());
6.Collectors.groupingBy与Collectors.toMap结合 先分组获取键值对(此时值为list,将list转为map)
//第二个map自定义键
Map<String, Map<String , XXVO>> map = lists.stream().collect(Collectors.groupingBy(XXVO::getA,Collectors.toMap(e -> e.getB() + e.getC(), XXVO-> XXVO)));