[英]Method to sort alpha after removing duplicates java (collections)
Working with collections and arraylists in java and writing a method to take user input (list) and put it into a method that removes the duplicates and then sorts the list alphabetically to print.使用 collections 和 java 中的数组列表,并编写一个方法来获取用户输入(列表)并将其放入一个删除重复项的方法中,然后按字母顺序对列表进行排序以打印。 The method I have written successfully removes duplicates, but will not sort alphabetically.
我编写的方法成功删除了重复项,但不会按字母顺序排序。 Here is my method body:
这是我的方法主体:
public static void sortNoDups(ArrayList<String> list) {
// e
ArrayList<String> printedList = new ArrayList<>();
System.out.println("\nWithout duplicates, sorted alphabetically:");
for (String i : list) {
if (!printedList.contains(i)) {
printedList.add(i);
Collections.sort(printedList);
System.out.print(i + " ");
}
}
System.out.println();
}
I have also tried it without the line "Collections.sort(printedList)", and with "Collections.sort(list)" to no avail.我也尝试过不使用“Collections.sort(printedList)”这一行,而使用“Collections.sort(list)”也无济于事。 Happy to include additional code from above if needed, but felt I should start specific to see if there are any glaring errors I'm just missing.
如果需要,很高兴从上面包含其他代码,但我觉得我应该开始具体看看是否有任何我刚刚遗漏的明显错误。
Your code is fine – it is correctly sorting printedList
– but you aren't actually printing that out.你的代码很好——它正确地排序
printedList
但你实际上并没有把它打印出来。 Right now, your code is iterating through the original list
.现在,您的代码正在遍历原始
list
。 The thing you are printing is System.out.print(i + " ");
您要打印的东西是
System.out.print(i + " ");
which is just printing the next string from list
.这只是打印
list
的下一个字符串。
To print the contents of the sorted printedList
, add this to the end of your method:要打印排序后的
printedList
的内容,请将其添加到方法的末尾:
for (String s : printedList) {
System.out.println(s);
}
Also, you might want to move Collections.sort(printedList)
to the end of the method as well.此外,您可能还希望将
Collections.sort(printedList)
移到方法的末尾。 That way, you'll call sort
one time at the end, instead of calling it each time in your for
loop.这样,您将在最后调用一次
sort
,而不是在for
循环中每次都调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.