写一点今天在写代码时遇到的问题:
1、使用stream流时多字段的排序问题
(1)多字段排序:使用Comparator.comparing,此时会对第一字段进行排序,如果第一字段相等,此时进入第二字段的排序Comparator.comparing().thenComparing(),接着,第三个字段···第n个字段均可使用.thenComparing()来实现;
value.stream()
.sorted(Comparator.comparing(TreeNodeAndIndex::getRow)
.thenComparing(TreeNodeAndIndex::getNodeVal)
(2)字段排序的自定义排序
value.stream()
.sorted(Comparator.comparing(TreeNodeAndIndex::getRow)
.thenComparing(TreeNodeAndIndex::getNodeVal,(x,y)-> y-x))
2、foreach使用时,其得到的参数是形参,并非实参;
在这样的一个写法下,TreeMap<Integet,List>中的list并不会被真正的排序,因为操作的并不是其真正的内存地址;
treeMap.forEach((key,value)-> value.stream()
.sorted(Comparator.comparing(TreeNodeAndIndex::getRow)
.thenComparing(TreeNodeAndIndex::getNodeVal,(x,y)-> y-x)));
那么如果要使得list真正的被排序应该按下面的方式写:
treeMap.forEach((key,value)-> {
List<TreeNodeAndIndex> sortedList = value.stream()
.sorted(Comparator.comparing(TreeNodeAndIndex::getRow)
.thenComparingInt(TreeNodeAndIndex::getNodeVal))
.collect(Collectors.toList());
treeMap.put(key,sortedList);
});