// private static List randomCharacters;
public static void main(String[] args) {
//Create List of Char type
List<Character> randomCharacters = new ArrayList<>();
//Character[] randChars = new Character[30];
//generate random letters and add to the list
for(int i = 0; i<30; i++){
int num = (int) (26* Math.random());
//randChars[i] = (char) (num + 'a');
char letter = (char) (num + 'a');
randomCharacters.add(letter);
//System.out.println(letter);
}
//System.out.println( "Unsorted list= " + Arrays.asList(randChars));
System.out.println( "Unsorted list= " + randomCharacters);
System.out.println("Ascending sort: ");
Arrays .stream(randomCharacters)
.sorted()
.collect(Collectors.toList());
}
我尝试过两种方式。一个使用Character Array并使用tolist转换它,只使用ArrayList但排序不起作用。关于为什么这不起作用的任何暗示。
答案 0 :(得分:4)
您可以拨打Stream.sorted()
和Stream.sorted(Comparator<? super T>)
以及Stream.distinct()
。像,
System.out.println("Unsorted list= " + randomCharacters);
System.out.println("Sorted Ascending: ");
randomCharacters.stream().sorted().forEach(System.out::println);
System.out.println("Sorted Descending: ");
randomCharacters.stream().sorted(Comparator.reverseOrder())
.forEach(System.out::println);
System.out.println("Ascending unique sort: ");
randomCharacters.stream().sorted().distinct().forEach(System.out::println);
答案 1 :(得分:3)
因为你打电话给&#34; .collect&#34;在流上,但不要将它存储在任何地方。然后打印未排序的列表(打印后将对列表进行排序)。 这样做
List<Character> sortedList = randomCharacters.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Ascending sort: " + sortedList);
答案 2 :(得分:0)
好的,谢谢你们,我们使用了你们两个方面的组合,这是我的完整代码。我觉得它对我需要的东西有好处,但是如果有人认为它可以更有效率让我知道 公共类RandomCharacters {
private static List<Character> randomCharacters;
public static void main(String[] args) {
//Create List of Char type
List<Character> randomCharacters = new ArrayList<>();
//generate random letters and add to the list
for(int i = 0; i<30; i++){
int num = (int) (26* Math.random());
char letter = (char) (num + 'a');
randomCharacters.add(letter);
}
System.out.println( "Unsorted list= " + randomCharacters);
List<Character> sortedList = randomCharacters.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Ascending sort: " + sortedList);
List<Character> reversedList = randomCharacters.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Sorted Descending: " + reversedList);
List<Character> uniqueList = randomCharacters.stream()
.sorted()
.distinct()
.collect(Collectors.toList());
System.out.println("Unique Sort: "+ uniqueList);
}
}
我会在上交之前添加更多评论