Java Stream Api

import java.util.*;

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

        List<Integer> nums = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
        System.out.println(nums);

        List<Integer> arr_nums = nums.stream().map(x -> x * x).toList();
        System.out.println(arr_nums);


        //With Multithreading - this will split and run in parallel cores
        List<Integer> cube_nums = nums.parallelStream().map(x -> x * x * x).toList();
        System.out.println(cube_nums);


        List<Integer> even_nums = nums.stream().filter(x -> x % 2 == 0).toList();
        System.out.println(even_nums);


        int sum_of_nums = nums.stream().reduce((t, x) -> t + x).orElse(0);
        System.out.println(sum_of_nums);

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *