Sunday, August 16, 2020

Java 8 Stream Sorting Multiple Fields Examples

Example to sort the stream on multiple fields using Comparaor.comparing() and Comparator.thenComparing() methods in java 8.

The below program is to sort the Employee list on name and age properties.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortMultipleFieldsSorted {

    public static void main(String[] args) {


        Employee e1 = new Employee(111, "Hari", 30);
        Employee e2 = new Employee(222, "Jool", 35);
        Employee e3 = new Employee(333, "Hari", 28);
        Employee e4 = new Employee(444, "Jool", 23);

        List<Employee> unsortredList = Arrays.asList(e1, e2, e3, e4);

        Comparator<Employee> idEmployeeComparator = Comparator.comparing(Employee::getName);

        Comparator<Employee> titleEmployeeComparator = Comparator.comparing(Employee::getAge);

        Comparator<Employee> multipleFieldsComparator = idEmployeeComparator.thenComparing(titleEmployeeComparator);

        System.out.println("Unsorted Emp List : ");

        for (Employee e : unsortredList) {
            System.out.println(e);
        }

        List<Employee> sortedList1 = unsortredList.stream().sorted(multipleFieldsComparator).collect(Collectors.toList());

        System.out.println("After sorting books list : ");


        for (Employee e : sortedList1) {
            System.out.println(e);
        }


        List<Employee> unsortredEmpList2 = Arrays.asList(e1, e2, e3, e4);

        System.out.println("Unsorted Books List 2 : ");
        for (Employee e : unsortredEmpList2) {
            System.out.println(e);
        }

        List<Employee> sortedList2 = unsortredEmpList2.stream().sorted(multipleFieldsComparator).collect(Collectors.toList());

        System.out.println("After sorting emp list 2: ");


        for (Employee e : sortedList2) {
            System.out.println(e);
        }
    }
}

class Employee {

    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Output:

Unsorted Emp List : 
Employee{id=111, name='Hari', age=30}
Employee{id=222, name='Jool', age=35}
Employee{id=333, name='Hari', age=28}
Employee{id=444, name='Jool', age=23}
After sorting books list : 
Employee{id=333, name='Hari', age=28}
Employee{id=111, name='Hari', age=30}
Employee{id=444, name='Jool', age=23}
Employee{id=222, name='Jool', age=35}
Unsorted Books List 2 : 
Employee{id=111, name='Hari', age=30}
Employee{id=222, name='Jool', age=35}
Employee{id=333, name='Hari', age=28}
Employee{id=444, name='Jool', age=23}
After sorting emp list 2: 
Employee{id=333, name='Hari', age=28}
Employee{id=111, name='Hari', age=30}
Employee{id=444, name='Jool', age=23}
Employee{id=222, name='Jool', age=35}


Comparaor.comparing()

Saturday, August 15, 2020

Java 8 Convert All Map Keys and Values into List

Java 8 Example to Convert All Map Keys and Values into List

Use keyset().stream() and call collect() method to convert into List.

Use values().stream() and call collect() method to convert into List.

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8MapToListExample {

    public static void main(String[] args) {

        Map<Integer, String> numbers = new HashMap<>();

        numbers.put(10, "ten");
        numbers.put(20, "twenty");
        numbers.put(30, "thirty");
        numbers.put(40, "forty");
        numbers.put(50, "fifty");

        //java 8 - convert all keys to map
        List<Integer> keysList = numbers.keySet().stream().collect(Collectors.toList());

        System.out.println("Map keys List :");

        for (Integer integer : keysList) {
            System.out.println(integer);
        }

        // java 8 - convert all keys to map
        List<String> valuesList = numbers.values().stream().collect(Collectors.toList());

        System.out.println("Map values list :");

        for (String s : valuesList) {
            System.out.println(s);
        }

        System.out.println("removing odd even fruit id's as list : ");

        List<Integer> evenList = numbers.keySet().stream().filter(id -> id % 2 == 0).collect(Collectors.toList());
        evenList.forEach(id -> System.out.println(id));
    }
}

Output:


Map keys List :
50
20
41
10
30
Map values list :
fifty
twenty
forty one
ten
thirty
removing odd even fruit id's as list : 
50
20
10
30


Java 8 Stream.iterate() VS Stream.random() - Infinite Streams


import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamGenerateVSIterate {

    public static void main(String[] args) {

        // Example to generate 10 random numbers from 0 to 20.
        Supplier<Integer> infiniteStream1 = () -> new Random().nextInt(20);

        List<Integer> randomNumbers = Stream.generate(infiniteStream1).limit(15).collect(Collectors.toList());

        System.out.println("10 random numbers list : " + randomNumbers);

        // Example to generate 10 random numbers from 0 to 20.
        Stream<Integer> infiniteStream2 = Stream.iterate(0, i -> i + 1);

        List<Integer> first10Numbers = infiniteStream2.limit(15).collect(Collectors.toList());

        System.out.println("first 10 numbers list : " + first10Numbers);

    }
}

Output:

15 random numbers list : [18, 3, 11, 4, 11, 5, 19, 3, 4, 5, 11, 7, 6, 0, 0]
first 15 numbers list : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]



Java 8 Stream.generate() - Generate Random UUID numbers from Infinite Series

 

package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamGenerateExample {

    public static void main(String[] args) {

        // Generates the UUID
        Supplier<UUID> randomUUIDSupplier = () -> UUID.randomUUID();

        List<UUID> uuidList = Stream.generate(randomUUIDSupplier).limit(15).collect(Collectors.toList());

        System.out.println("10 random UUID list : "+uuidList);

    }
}

Output:

10 random UUID list : 

[781bce19-1dfd-4564-b220-80fb7aa850bc, a24d411a-7d5a-4447-9f5b-77f366dfd853, ccfd492e-78a4-47f7-9941-366cd60368c7, 3a97b09d-5e47-4814-8075-098ed516572d, 3ea7aaaf-04b9-4a12-b97c-e32e0ac0db80, d98690b7-696f-4355-b1e8-ce381378f490, 173d0497-dd8f-401f-8d39-30b2ddca8cf4, 7880e981-3265-4ebf-a73e-0c706c5b21f6, ac255ce3-a964-4d15-bf9c-13b5834cbc88, 6aa279ee-32b7-4e14-b689-d1586b8b124a, 0e1dd672-99d1-498d-93cf-1ddefb9bfc34, d9dd7643-83c9-44cb-a669-483e1e6c877e, 98f3018f-a7c1-4dbb-b391-8a1d2885553a, aa75f989-01e3-4b15-93ab-5096068f26a4, ad762c3b-9a66-438a-801c-8e3c48f8a223]



Java 8 Stream.iterate() Infinite Streams Example

Java 8 Example program to generate the first 10 numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> integerInfiniteStream = Stream.iterate(1, i -> i +1);

        List<Integer> first10Numbers = integerInfiniteStream.limit(10).collect(Collectors.toList());

        System.out.println("integerInfiniteStream with limit 10 : "+first10Numbers);

    }
}

Output:

integerInfiniteStream with limit 10 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Java 8 Example program to generate the 10 ten even numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> even10Numbers = Stream.iterate(0, i -> i +2);

        List<Integer> first10Numbers = even10Numbers.limit(10).collect(Collectors.toList());

        System.out.println("even10Numbers with limit 10 : "+first10Numbers);

    }
}

Output:

even10Numbers with limit 10 : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]



Tuesday, April 14, 2020

Java 8 flatMap Examples - Stream flatmap convert Stream<List<List<String>>> into Stream<String>

1. Introduction


In this article, We'll learn about java 8 new Stream API flatMap() method. When to use it and how to use it.

flatMap() method is used to convert or flatten Stream of collections into Stream of collection values by removing the collection.

Removing collection such as List or Set from Stream is called flattening.

FlatMap() is part of Stream Intermediate Operations in Java 8.

Java 8, Stream can hold any type of collections and can be converted into Stream<T> as below.

Stream<List<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<Set<Set<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<Object>>> --> apply flatMap() logic --> Stream<Object>


Sunday, April 12, 2020

Java 8 Optional orElseThrow() Example | Throw Exception in Optional in Java 8

1. introduction


In this tutorial, We'll learn how to throw an exception if the option is empty. Optional API orElseThrow() method returns value from Optional if present. Otherwise, it will throw the exception created by the Supplier.

2. Syntax


public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                                    throws X extends Throwable


Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

A method reference to the exception constructor with an empty argument list can be used as the supplier. For example, IllegalStateException::new, ArithmeticException::new

Java 8 Optional orElseGet() Example

1. Introduction

In this tutorial, We'll learn java 8 Optional API orElseGet() method examples and where to use.

2. Syntax

[lock]
public T orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation. This method takes the Supplier Functional Interface. [/lock]

if the Supplier is null, it throws NullPointerException.