【发布时间】: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