List<Integer> list = new LinkedList<Integer>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a number, -1 to exit: ");
int num = scanner.nextInt();
if (num == -1) break;
list.add(num);
}
// sort the list (ascending)
Collections.sort(list);
// output the list
for (Integer val : list) {
System.out.println(val);
}
SortedSet<Integer> sortedSet = new TreeSet<Integer>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Enter a number, -1 to exit: ");
int num = scanner.nextInt();
if (num == -1)
break;
sortedSet.add(num);
}
System.out.println(sortedSet);
4条答案
按热度按时间62o28rlo1#
hof1towb2#
您可以使用流:
tcomlyy63#
使用SortedSet进行默认排序,不使用重复项。(如果此处需要重复项,请不要使用!)
sxpgvts34#
仅在if条件下尝试!