Sort List> based on the Integer in the second index of the inner List?

huangapple go评论71阅读模式
英文:

Sort List<List<Integer>> based on the Integer in the second index of the inner List<Integer>?

问题

Sure, here's the translation:

假设我有以下输入:

[[5,3,6,7],[2,1,6,3],[3,2,6,3],[5,4,4,3]]

如何根据每个列表的第二个数字进行排序,使得我得到以下结果:(因为 1 < 2 < 3 < 4)

[[2,1,6,3],[3,2,6,3],[5,3,6,7],[5,4,4,3]]

我想你可以使用流(Streams)做一些操作,但我还没完全弄明白。

英文:

Imagine I have the following input:

[[5,3,6,7],[2,1,6,3],[3,2,6,3],[5,4,4,3]]

How could I sort it based on the second number of each list, so that I have the following: (because 1 < 2 < 3 < 4)

[[2,1,6,3],[3,2,6,3],[5,3,6,7],[5,4,4,3]]

I imagine you can do something with Streams, but I haven't quite figured it out.

答案1

得分: 3

好的,以下是您要求的翻译内容:

这其实非常简单。您可以查看列表排序和自定义比较器。

public static void sortBySecondIndex(List<List<Integer>> data) {
    data.sort(Comparator.comparingInt(one -> one.get(1)));        
}
英文:

Well, this is very simple. Actually you can look at list sorting and custom comparator.

public static void sortBySecondIndex(List&lt;List&lt;Integer&gt;&gt; data) {
    data.sort(Comparator.comparingInt(one -&gt; one.get(1)));        
}

答案2

得分: 1

list.sort((a, b) -> a.get(1).compareTo(b.get(1)));
英文:
list.sort((a, b) -&gt; a.get(1).compareTo(b.get(1)));

huangapple
  • 本文由 发表于 2020年9月29日 17:23:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64116650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定