Please wait...

小波Note

四川 · 成都市11 ℃
English

Java Stream

成都 (cheng du)8/27/2024, 5:45:33 PM2.77kEstimated reading time 9 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer
java
        import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class StreamExamples {

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("apple", "banana", "cherry", "date", "elderberry", "fig", "grape");

        // Filtering: Keep strings with length greater than 5
        List<String> filtered = strings.stream()
                .filter(s -> s.length() > 5)
                .collect(Collectors.toList());
        System.out.println("Filtered: " + filtered);

        // Mapping: Convert all strings to uppercase
        List<String> mapped = strings.stream()
                .map(String::toUpperCase)
                .collect(Collectors.toList());
        System.out.println("Mapped: " + mapped);

        // Sorting: Sort alphabetically
        List<String> sorted = strings.stream()
                .sorted()
                .collect(Collectors.toList());
        System.out.println("Sorted: " + sorted);

        // Counting: Calculate the total length of strings
        int totalLength = strings.stream()
                .mapToInt(String::length)
                .sum();
        System.out.println("Total Length: " + totalLength);

        // Finding: Find the first string that starts with the letter 'c'
        Optional<String> firstWithC = strings.stream()
                .filter(s -> s.startsWith("c"))
                .findFirst();
        firstWithC.ifPresent(s -> System.out.println("First with 'c': " + s));

        // Grouping: Group by string length
        Map<Integer, List<String>> groupedByLength = strings.stream()
                .collect(Collectors.groupingBy(String::length));
        System.out.println("Grouped by Length: " + groupedByLength);

        // Joining: Join all strings into one string, separated by commas
        String joined = strings.stream()
                .collect(Collectors.joining(", "));
        System.out.println("Joined: " + joined);

        // Distinct: Remove duplicate strings
        List<String> distinct = strings.stream()
                .distinct()
                .collect(Collectors.toList());
        System.out.println("Distinct: " + distinct);

        // Limiting: Limit the result to 3 elements
        List<String> limited = strings.stream()
                .limit(3)
                .collect(Collectors.toList());
        System.out.println("Limited: " + limited);

        // Skipping: Skip the first 3 elements
        List<String> skipped = strings.stream()
                .skip(3)
                .collect(Collectors.toList());
        System.out.println("Skipped: " + skipped);
    }
}