Bob*_*Bob 2 java arrays sorting collections arraylist
我有Double Array列表,我想根据第一个和最后一个字段对它进行排序.到目前为止,我只能通过1个数组元素对其进行排序.
真实状态:
0 1 2
------- ------- -------
78 100 0
78 100 1
0 100 0
104 100 1
Run Code Online (Sandbox Code Playgroud)
预期:
0 1 2
------- ------- -------
0 100 0
78 100 1
78 100 0
101 100 1
Run Code Online (Sandbox Code Playgroud)
我想根据Array的第一个元素的值对字段进行排序.如果第1和第2的值相等,我想根据第3个元素排序,其中first应该是1然后是0(将只有1和0值)
List<Double[]> splitList = new ArrayList<>();
Double[] tmp1 = { 78d, 100d, 0d };
Double[] tmp2 = { 78d, 100d, 1d };
Double[] tmp3 = { 0d, 100d, 0d };
Double[] tmp4 = { 104d, 100d, 1d };
splitList.add(tmp1);
splitList.add(tmp2);
splitList.add(tmp3);
splitList.add(tmp4);
splitList.sort(Comparator.comparingDouble(a -> a[0]));
Run Code Online (Sandbox Code Playgroud)
这个根据第一个元素排序.我发现解决方案按两个元素排序/sf/answers/1880558571/所以我试了一下:
splitList.sort(Comparator.comparingDouble(a -> a[0]).thenComparingDouble(b -> b[2]));
Run Code Online (Sandbox Code Playgroud)
它输出一个错误:
Multiple markers at this line
- The type of the expression must be an array type but it resolved
to Object
- The type of the expression must be an array type but it resolved
Run Code Online (Sandbox Code Playgroud)
如何比较List of Array?
似乎java编译器在推断泛型类型方面存在问题,您有一些选项可以解决此问题:
使用带有模式的类型提示Class.<GenericType>.method(Arguments)
:
splitList.sort(Comparator.<Double[]>comparingDouble(a -> a[0]).thenComparingDouble(b -> b[2]));
Run Code Online (Sandbox Code Playgroud)声明lambda参数类型(声明第一个似乎就足够了):
splitList.sort(Comparator.comparingDouble((Double[] a) -> a[0]).thenComparingDouble(b -> b[2]));
Run Code Online (Sandbox Code Playgroud)阅读完评论后,您想要反转上次比较,可以这样做:
Comparator.<Double[]>comparingDouble(a -> a[0])
.thenComparing(Comparator.<Double[]>comparingDouble(b -> b[2]).reversed())
Run Code Online (Sandbox Code Playgroud)
这是非常混乱的,你最好使用这样的东西:
splitList.sort((a, b) -> {
int c = Double.compare(a[0], b[0]);
return c == 0 ? Double.compare(b[2], a[2]) : c;
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
55 次 |
最近记录: |