Java List Stream Grouping and Ordering: A Comprehensive Guide
In Java, you can use the Collectors.groupingBy method to group elements of a List based on a specific criterion. Here is an example:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "orange", "grape", "pear", "mango");
// Group fruits by their length
Map<Integer, List<String>> groupedByLength = fruits.stream()
.collect(Collectors.groupingBy(String::length));
//Print the groups
groupedByLength.forEach((length, group) -> System.out.println(length + ": " + group));
}
}
This will output:
3: [pear]
5: [apple, grape, mango]
6: [orange, banana]
The groupedByLength map contains the groups where the key is the length of the fruits and the value is a list of fruits with that length.
You can also specify the order of the groups by using the Collectors.groupingBy method with a LinkedHashMap as the downstream collector. This will maintain the insertion order of the groups:
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> fruits = Arrays.asList("apple", "banana", "orange", "grape", "pear", "mango");
// Group fruits by their length in order of appearance
Map<Integer, List<String>> groupedByLength = fruits.stream()
.collect(Collectors.groupingBy(String::length, LinkedHashMap::new, Collectors.toList()));
//Print the groups
groupedByLength.forEach((length, group) -> System.out.println(length + ": " + group));
}
}
This will output:
5: [apple, grape, mango]
6: [orange, banana]
3: [pear]
In this example, the groupedByLength map maintains the order in which the groups were inserted into the map.
原文地址: https://www.cveoy.top/t/topic/qDBq 著作权归作者所有。请勿转载和采集!