我很难理解正确的语法来对Map进行排序,这些值不仅是一种类型,而且可以再次嵌套。我会在这里尝试提出一个合适的例子:
首先让我们为它创建一个随机类:
class NestedFoo{
int valA;
int valB;
String textA;
public NestedFoo(int a, int b, String t){
this.valA = a;
this.valB = b;
this.textA = t;
}
}
好吧,那是我们的班级。清单如下:
HashMap<Integer, ArrayList<NestedFoo>> sortmePlz = new HashMap<>();
首先创建3个条目,它们应该已经显示了排序工作。
ArrayList<NestedFoo> l1 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,2,"a");
n3 = new NestedFoo(1,4,"c");
l1.add(n1);
l1.add(n2);
l1.add(n3);
ArrayList<NestedFoo> l2 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,2,"a");
n3 = new NestedFoo(2,2,"b");
n4 = new NestedFoo(1,4,"c");
l2.add(n1);
l2.add(n2);
l2.add(n3);
l2.add(n4);
ArrayList<NestedFoo> l3 = new ArrayList<>();
n1 = new NestedFoo(3,2,"a");
n2 = new NestedFoo(2,3,"b");
n3 = new NestedFoo(2,2,"b");
n4 = new NestedFoo(5,4,"c");
l3.add(n1);
l3.add(n2);
l3.add(n3);
l3.add(n4);
甜蜜的,现在将它们放入我们的地图。
sortmePlz.put(5,l1);
sortmePlz.put(2,l2);
sortmePlz.put(1,l3);
我现在想要的是首先按其键对整个地图进行排序,因此顺序应为l3 l2 l1。然后,我希望每个键内的列表按以下顺序排序:intA,intB,text(全部升序)
我不知道该怎么做。尤其是自从Java 8包含所有这些lambda以来,我没有试着阅读这个主题,但是对那里的代码感到不知所措。
提前致谢!我希望代码没有任何语法错误,我可以随时进行修改
您可以使用TreeSet
而不是常规HashMap
值,并且您的值将自动按以下顺序排序key
:
Map<Integer, ArrayList<NestedFoo>> sortmePlz = new TreeMap<>();
第二步,我有点困惑。
按以下顺序排序:intA,intB,text(全部升序)
我想您想通过首先比较这些intA
值对列表进行排序,然后如果它们相等,则用by by进行比较intB
,依此类推。如果我对您的理解正确,则可以Comparator
与comparing
和一起使用thenComparing
。
sortmePlz.values().forEach(list -> list
.sort(Comparator.comparing(NestedFoo::getValA)
.thenComparing(NestedFoo::getValB)
.thenComparing(NestedFoo::getTextA)));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句