英文:
How I can sort a list of list in java?
问题
我想对一个列表的列表进行排序,示例:
List<List<String>> listOflists = new ArrayList();
List<String> b = {"x", "x"};
List<String> a = {"x"};
List<String> c = {"x", "x", "x"};
listOflists.add(a);
listOflists.add(b);
listOflists.add(c);
//按数组大小排序
List<String> sortedList = listOflists.stream().sorted().collect(Collectors.toList());
我预期在forEach过程中处理listOflists:
循环 1 x
循环 2 x,x
循环 3 x,x,x
英文:
I want to sort a list of lists, example:
List<List<String>> listOflists = new ArrayList();
List<String> b = {"x", "x"};
List<String> a = {"x"};
List<String> c = {"x", "x", "x"};
listOflists.add(a);
listOflists.add(b);
listOflists.add(c);
//Oder by size of the array
List<String> sortedList = listOflists.stream().sorted().collect(Collectors.toList());
I expected that listOflists in a forEach process:
Lopp 1 x
Lopp 2 x,x
Lopp 3 x,x,x
答案1
得分: 1
[Arrays.compare](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Arrays.html#compare(T%5B%5D,T%5B%5D)) 函数用于比较两个对象数组,比较的是具有可比性的元素的字典顺序。
试一试:
List<List<String>> listOflists = Arrays.asList(
Arrays.asList("x", "x"),
Arrays.asList("x"),
Arrays.asList("x", "x", "x")
);
List<List<String>> sortedList = listOflists.stream()
.map(list -> list.toArray(String[]::new))
.sorted((x, y) -> Arrays.compare(x, y))
.map(array -> Arrays.asList(array))
.collect(Collectors.toList());
System.out.println(sortedList);
输出结果:
[[x], [x, x], [x, x, x]]
如果你想根据列表大小进行排序:
List<List<String>> sortedList = listOflists.stream()
.sorted(Comparator.comparing(list -> list.size()))
.collect(Collectors.toList());
英文:
Arrays.compare compares two Object arrays, within comparable elements, lexicographically.
Try this.
List<List<String>> listOflists = Arrays.asList(
Arrays.asList("x", "x"),
Arrays.asList("x"),
Arrays.asList("x", "x", "x")
);
List<List<String>> sortedList = listOflists.stream()
.map(list -> list.toArray(String[]::new))
.sorted((x, y) -> Arrays.compare(x, y))
.map(array -> Arrays.asList(array))
.collect(Collectors.toList());
System.out.println(sortedList);
output:
[[x], [x, x], [x, x, x]]
If you want to sort by list size.
List<List<String>> sortedList = listOflists.stream()
.sorted(Comparator.comparing(list -> list.size()))
.collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论