In Java, you can use the Stream API to perform various operations on a List, including grouping elements based on certain criteria. Here is an example of how you can use the Stream API to group elements in a List:

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> names = Arrays.asList('John', 'Jane', 'Adam', 'Eve', 'Alan', 'Alex');

        // Group names by their first letter
        Map<Character, List<String>> groupedNames = names.stream()
                .collect(Collectors.groupingBy(name -> name.charAt(0)));

        // Print the grouped names
        groupedNames.forEach((key, value) -> System.out.println(key + ': ' + value));
    }
}

Output:

A: [Adam, Alan, Alex]
J: [John, Jane]
E: [Eve]

In the above example, we create a List of names and use the stream() method to convert it into a Stream. Then, we use the collect() method along with Collectors.groupingBy() to group the names based on their first letter. Finally, we print the grouped names using the forEach() method on the resulting Map.

Java Stream API: Grouping Elements in a List

原文地址: https://www.cveoy.top/t/topic/qDA7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录