</>

Technology

Java Programs

Difficulty

Advanced

Interview Question

Write a Java program demonstrating Java 8 Streams — filter, map, collect, reduce, flatMap, groupingBy, partitioningBy.

Answer

Java 8 Streams — Complete Deep Dive

Java
import java.util.*;
import java.util.stream.*;
import java.util.function.*;

public class StreamsDeepDive {
    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        List<String>  tools   = Arrays.asList(
            "Selenium", "TestNG", "Cucumber", "Maven", "Jenkins",
            "Postman", "Selenium", "Appium", "JMeter"
        );

        // ─── FILTER ───
        List<Integer> evens = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        System.out.println("Evens: " + evens);  // [2, 4, 6, 8, 10]

        // ─── MAP ───
        List<String> upperTools = tools.stream()
            .map(String::toUpperCase)
            .collect(Collectors.toList());
        System.out.println("Upper: " + upperTools);

        // ─── MAP to different type ───
        List<Integer> lengths = tools.stream()
            .map(String::length)
            .collect(Collectors.toList());
        System.out.println("Lengths: " + lengths);

        // ─── FILTER + MAP + COLLECT ───
        List<String> longToolsUpper = tools.stream()
            .filter(t -> t.length() > 6)        // keep tools with >6 chars
            .map(String::toUpperCase)            // convert to uppercase
            .sorted()                            // alphabetical order
            .distinct()                          // remove duplicates
            .collect(Collectors.toList());
        System.out.println("Long tools: " + longToolsUpper);

        // ─── REDUCE ───
        int sum = numbers.stream()
            .reduce(0, Integer::sum);            // 0 is identity, sum accumulator
        System.out.println("Sum: " + sum);       // 55

        Optional<Integer> product = numbers.stream()
            .reduce((a, b) -> a * b);
        System.out.println("Product: " + product.get());  // 3628800

        // ─── COUNT ───
        long countLong = tools.stream()
            .filter(t -> t.length() > 5)
            .count();
        System.out.println("Tools > 5 chars: " + countLong);

        // ─── findFirst / findAny ───
        Optional<String> first = tools.stream()
            .filter(t -> t.startsWith("S"))
            .findFirst();
        first.ifPresent(t -> System.out.println("First S: " + t));  // Selenium

        // ─── anyMatch / allMatch / noneMatch ───
        boolean hasSelenium   = tools.stream().anyMatch(t -> t.equals("Selenium"));
        boolean allUpperCheck = tools.stream().allMatch(t -> t.length() > 2);
        boolean noNumbers     = tools.stream().noneMatch(t -> t.matches(".*\\d.*"));
        System.out.println("Has Selenium: " + hasSelenium);   // true
        System.out.println("All > 2 chars: " + allUpperCheck); // true
        System.out.println("No numbers in names: " + noNumbers); // true

        // ─── MIN / MAX ───
        Optional<Integer> max = numbers.stream().max(Integer::compareTo);
        Optional<Integer> min = numbers.stream().min(Integer::compareTo);
        System.out.println("Max: " + max.get() + ", Min: " + min.get());  // 10, 1

        // ─── SORTED with Comparator ───
        List<String> sortedByLength = tools.stream()
            .sorted(Comparator.comparingInt(String::length))
            .collect(Collectors.toList());
        System.out.println("By length: " + sortedByLength);

        // ─── DISTINCT ───
        List<String> distinctTools = tools.stream()
            .distinct()
            .collect(Collectors.toList());
        System.out.println("Distinct: " + distinctTools);

        // ─── LIMIT / SKIP ───
        List<Integer> top3 = numbers.stream().limit(3).collect(Collectors.toList());
        List<Integer> skip3 = numbers.stream().skip(3).collect(Collectors.toList());
        System.out.println("Top 3:  " + top3);   // [1, 2, 3]
        System.out.println("Skip 3: " + skip3);  // [4, 5, 6, 7, 8, 9, 10]
    }
}

flatMap — Flatten Nested Collections

Java
List<List<String>> nested = Arrays.asList(
    Arrays.asList("Selenium", "TestNG"),
    Arrays.asList("Cucumber", "Maven"),
    Arrays.asList("Jenkins", "Postman")
);

List<String> flat = nested.stream()
    .flatMap(Collection::stream)    // flatten List<List<String>> → Stream<String>
    .collect(Collectors.toList());

System.out.println("Flat: " + flat);
// → [Selenium, TestNG, Cucumber, Maven, Jenkins, Postman]

// Split sentence into words and collect all
List<String> sentences = Arrays.asList("Hello World", "Java Streams", "are great");
List<String> words = sentences.stream()
    .flatMap(s -> Arrays.stream(s.split(" ")))
    .collect(Collectors.toList());
System.out.println("Words: " + words);
// → [Hello, World, Java, Streams, are, great]

Collectors.groupingBy — Group Elements

Java
List<String> tools = Arrays.asList(
    "Selenium", "TestNG", "Cucumber", "Maven", "Jenkins", "Postman", "Appium"
);

// Group by first letter
Map<Character, List<String>> byFirstLetter = tools.stream()
    .collect(Collectors.groupingBy(t -> t.charAt(0)));
System.out.println("By first letter: " + byFirstLetter);

// Group by length
Map<Integer, List<String>> byLength = tools.stream()
    .collect(Collectors.groupingBy(String::length));
System.out.println("By length: " + byLength);

// Count in each group
Map<Integer, Long> countByLength = tools.stream()
    .collect(Collectors.groupingBy(String::length, Collectors.counting()));
System.out.println("Count by length: " + countByLength);

Output

CODE
By first letter: {A=[Appium], C=[Cucumber], J=[Jenkins], M=[Maven], P=[Postman], S=[Selenium], T=[TestNG]}
By length: {6=[TestNG, Appium], 7=[Selenium, Jenkins, Postman], 8=[Cucumber]}
Count by length: {6=2, 7=3, 8=1}

Collectors.partitioningBy — Split into Two Groups

Java
// Split numbers into even and odd
Map<Boolean, List<Integer>> partitioned = numbers.stream()
    .collect(Collectors.partitioningBy(n -> n % 2 == 0));

System.out.println("Even: " + partitioned.get(true));   // [2,4,6,8,10]
System.out.println("Odd:  " + partitioned.get(false));  // [1,3,5,7,9]

// Split tools by length > 6
Map<Boolean, List<String>> toolParts = tools.stream()
    .collect(Collectors.partitioningBy(t -> t.length() > 6));
System.out.println("Long:  " + toolParts.get(true));
System.out.println("Short: " + toolParts.get(false));

Collectors.joining — Concatenate Strings

Java
String joined = tools.stream()
    .collect(Collectors.joining(", "));
System.out.println(joined);  // Selenium, TestNG, Cucumber, Maven, Jenkins, Postman, Appium

String withBrackets = tools.stream()
    .collect(Collectors.joining(", ", "[", "]"));
System.out.println(withBrackets);  // [Selenium, TestNG, Cucumber, Maven, Jenkins, Postman, Appium]

Collectors.toMap — Convert to Map

Java
List<String> tools = Arrays.asList("Selenium", "TestNG", "Cucumber");

Map<String, Integer> toolLengthMap = tools.stream()
    .collect(Collectors.toMap(
        t -> t,           // key: tool name
        String::length    // value: length
    ));
System.out.println(toolLengthMap);
// {Selenium=8, TestNG=6, Cucumber=8}

IntStream / LongStream / DoubleStream

Java
// Range of numbers
IntStream.range(1, 6).forEach(i -> System.out.print(i + " "));
// → 1 2 3 4 5

IntStream.rangeClosed(1, 5).forEach(i -> System.out.print(i + " "));
// → 1 2 3 4 5

// Sum, average, statistics
IntSummaryStatistics stats = IntStream.of(1,2,3,4,5,6,7,8,9,10).summaryStatistics();
System.out.println("Sum: "   + stats.getSum());      // 55
System.out.println("Avg: "   + stats.getAverage());  // 5.5
System.out.println("Max: "   + stats.getMax());      // 10
System.out.println("Count: " + stats.getCount());    // 10

Method References with Streams

Java
List<String> tools = Arrays.asList("selenium", "testng", "cucumber");

// :: method reference types:
tools.stream().map(String::toUpperCase).forEach(System.out::println);  // instance method ref
tools.stream().filter(Objects::nonNull).collect(Collectors.toList());   // static method ref

// Custom class method reference
tools.stream().map(StringUtils::capitalize).collect(Collectors.toList()); // if method exists

Parallel Streams (Faster for Large Data)

Java
List<Integer> bigList = IntStream.rangeClosed(1, 1_000_000)
    .boxed().collect(Collectors.toList());

// Sequential
long seqSum = bigList.stream().mapToLong(Integer::longValue).sum();

// Parallel (uses ForkJoinPool — multiple CPU cores)
long parSum = bigList.parallelStream().mapToLong(Integer::longValue).sum();

System.out.println("Sequential sum: " + seqSum);
System.out.println("Parallel sum:   " + parSum);  // same result, faster

Automation Testing Relevance

Java
List<WebElement> products = driver.findElements(By.css(".product-card"));

// Get all product names that are in stock
List<String> inStockNames = products.stream()
    .filter(p -> p.findElement(By.css(".stock")).getText().equals("In Stock"))
    .map(p -> p.findElement(By.css(".name")).getText())
    .collect(Collectors.toList());

// Get prices sorted ascending
List<Double> sortedPrices = products.stream()
    .map(p -> Double.parseDouble(
        p.findElement(By.css(".price")).getText().replace("$", "")))
    .sorted()
    .collect(Collectors.toList());

// Find most expensive product
Optional<WebElement> expensive = products.stream()
    .max(Comparator.comparingDouble(p ->
        Double.parseDouble(p.findElement(By.css(".price")).getText().replace("$", ""))));

expensive.ifPresent(p -> System.out.println("Most expensive: " +
    p.findElement(By.css(".name")).getText()));

Follow AutomateQA