java list stream group sort
To sort and group a List using Stream in Java, you can follow these steps:
- Create a List of objects.
List<YourObject> list = new ArrayList<>();
list.add(new YourObject("Object1", 10));
list.add(new YourObject("Object2", 20));
list.add(new YourObject("Object3", 10));
list.add(new YourObject("Object4", 20));
- Use the
stream()method to convert the List into a Stream.
Stream<YourObject> stream = list.stream();
- Use the
collect()method to group and sort the objects in the Stream.
Map<Integer, List<YourObject>> groupedAndSortedMap = stream
.collect(Collectors.groupingBy(YourObject::getSomeProperty, TreeMap::new, Collectors.toList()));
In the groupingBy() method, you specify the property by which you want to group the objects (in this example, getSomeProperty()), and it creates a Map where the key is the property value and the value is a List of objects with that property value. The TreeMap::new parameter is used to create a sorted map based on the keys.
- Now, you can iterate over the grouped and sorted map to access the objects.
for (Map.Entry<Integer, List<YourObject>> entry : groupedAndSortedMap.entrySet()) {
int key = entry.getKey();
List<YourObject> objects = entry.getValue();
System.out.println("Key: " + key);
for (YourObject object : objects) {
System.out.println(object.getName());
}
}
This will print the grouped and sorted objects based on the specified property.
Note: Replace YourObject with the actual class name of your objects, and getSomeProperty() with the actual method name that returns the property value for grouping and sorting
原文地址: http://www.cveoy.top/t/topic/iXB7 著作权归作者所有。请勿转载和采集!