简体   繁体   English

按内部列表的第一个元素对列表列表进行排序(Java或groovy)

[英]Sorting a list of lists by the first element of inner list (Java or groovy)

I have a list which contains a list of strings like so... 我有一个包含像这样的字符串列表的列表...

 ["Running Shoes", "Men's Shoes", "Men's Walking Shoes"]
 ["Team Sports", "Ice Hockey", "Recreational Ice Skates"]
 ["Pro Sports", "Baseball", "Baseball Gloves", "Adult Gloves"]

I want to sort this list by the first element in the sublist, meaning the element at index 0. So in this example after the sort, the 'Running Shoes' element would be first, followed by 'Pro Sports' element and last would 'Team Sports'. 我想按子列表中的第一个元素(即索引0处的元素)对该列表进行排序。因此,在此示例中,排序后,“ Running Shoes”元素将是第一个,其次是“ Pro Sports”元素,最后一个是“团队竞技'。

Could you someone give some pointers or share some code? 有人可以指点一下还是共享一些代码? In Java or Groovy. 在Java或Groovy中。

In groovy: 时髦:

list.sort { it[0][0] }

If you don't want to mutate the original list, and return the sorted list, you can do 如果您不想更改原始列表,并返回排序后的列表,则可以

list.sort(false) { it[0][0] }

Well, P comes before R, so if I'm understanding the problem correctly, the order would be 'Pro Sports, Baseball', 'Running Shoes', and 'Team Sports'. 好吧,P位于R之前,因此,如果我正确理解问题,则顺序为“专业运动,棒球”,“跑步鞋”和“团队运动”。 You can sort this easily with Groovy like this: 您可以使用Groovy这样轻松地对它进行排序:

[
     ["Running Shoes", "Men's Shoes", "Men's Walking Shoes"],
     ["Team Sports", "Ice Hockey", "Recreational Ice Skates"],
     ["Pro Sports", "Baseball", "Baseball Gloves", "Adult Gloves"]
].toSorted { a, b -> a[0] <=> b[0] }

The output looks like this: 输出看起来像这样:

[
    ['Pro Sports', 'Baseball', 'Baseball Gloves', 'Adult Gloves'],
    ['Running Shoes', "Men's Shoes", "Men's Walking Shoes"],
    ['Team Sports', 'Ice Hockey', 'Recreational Ice Skates']
]

You can also go the long way with a Comparator: 您也可以使用比较器进行大量改进:

class ListComparator implements Comparator<List> {
    int compare(List obj1, List obj2) {
        obj1[0].compareTo(obj2[0])
    }

    boolean equals(Object obj) {
        this == obj
    }
}

[
     ["Running Shoes", "Men's Shoes", "Men's Walking Shoes"],
     ["Team Sports", "Ice Hockey", "Recreational Ice Skates"],
     ["Pro Sports", "Baseball", "Baseball Gloves", "Adult Gloves"]
].toSorted( new ListComparator()) == [
    ['Pro Sports', 'Baseball', 'Baseball Gloves', 'Adult Gloves'],
    ['Running Shoes', "Men's Shoes", "Men's Walking Shoes"],
    ['Team Sports', 'Ice Hockey', 'Recreational Ice Skates']
]

Hint 暗示

You're getting down votes because you can learn this by reading Groovy's documentation. 您之所以落选,是因为您可以阅读Groovy的文档来学习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM