【问题标题】:How do I sort the lists by the second word? [duplicate]如何按第二个单词对列表进行排序? [复制]
【发布时间】:2019-02-06 10:44:22
【问题描述】:

我有一个包含如下数据的集合:

John eats candy
Richard runs around in the morning
Hannah drinks water

我把每个单词分开,添加到数组中得到:

[John, eats, candy]
[Richard, runs, around, in, the, morning]
[Hannah, drinks, water]

输出应该是(第二个单词按字母顺序排序)

[Hannah, drinks, water]
[John, eats, candy]
[Richard, runs, around, in, the, morning]

这是我的代码:

        List<List<String>> mainList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (String s : array) {
            String[] x = s.split(" ");
            for (int i = 0; i < x.length; i++) {
                list.add(x[i]);
            }
            mainList.add(list);
            list = new ArrayList<>();
        }

但我不知道下一步该做什么。如何实现元素的比较,并在此基础上替换行。 将字符串划分为数组以访问第二个元素是否正确? 即使您只是提出建议,我也会很高兴。

【问题讨论】:

  • 提示 1:首先尝试编写一个获取其中两个列表并返回 int 值的方法:如果第二个列表“大于”首先,如果它“小于”第一个,则为 -1,如果它们“相等”,则为 0。 提示 2: 请注意,有些行可能只包含一个单词。 提示 3: 在 Java API 文档中查找 Collections.sort()。 (或者 List.sort() 如果您使用的是 Java 8。)
  • @biziclop 我会因为重复关闭它而感觉非常糟糕,但是在你的 cmets 之后,你让我的生活更轻松了。谢谢

标签: java sorting arraylist collections


【解决方案1】:

第一次尝试,你可以写一个Comparator

class ListComparator implements Comparator<List<String>> {
    @Override
    public int compare(List<String> o1, List<String> o2) {
        return o1.get(1).compareTo(o2.get(1));
    }
}

mainList.sort(new ListComparator());

在 java-8 中,可以缩短为:

mainList.sort(Comparator.comparing(strings -> strings.get(1))); // compare using the second element(index 1) of every list

【讨论】:

  • 看起来 OP 不会理解这一点......
  • @Eugene 从那时起。但我认为这可能没有必要。既然能妥善解决问题...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
相关资源
最近更新 更多