Thursday, 18 May 2023

Construct a map from array of objects using streams

Below snippet get the map from employees array, where key is the employee id and object is employee itself.

Map<Integer, Employee> empById = unmodifiableMap(Arrays.stream(emps).collect(Collectors.toMap(Employee::getId, identity())));

Find the below working application.

 

MapFromArray.java

package com.sample.app.collections;

import static java.util.Collections.unmodifiableMap;
import static java.util.function.Function.identity;

import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class MapFromArray {

    private static class Employee {
        private int id;
        private String name;

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

        public int getId() {
            return id;
        }

        @Override
        public String toString() {
            return "Employee [id=" + id + ", name=" + name + "]";
        }

    }

    public static void main(String[] args) {
        Employee emp1 = new Employee(1, "Krishna");
        Employee emp2 = new Employee(2, "Krishna");
        Employee emp3 = new Employee(3, "Krishna");
        Employee emp4 = new Employee(4, "Krishna");

        Employee[] emps = { emp1, emp2, emp3, emp4 };

        Map<Integer, Employee> empById = unmodifiableMap(
                Arrays.stream(emps).collect(Collectors.toMap(Employee::getId, identity())));

        for (Entry<Integer, Employee> entry : empById.entrySet()) {
            System.out.println(entry.getKey() + "\t" + entry.getValue());
        }
    }

}

Output

1   Employee [id=1, name=Krishna]
2   Employee [id=2, name=Krishna]
3   Employee [id=3, name=Krishna]
4   Employee [id=4, name=Krishna]



 

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Get the stream from Enumeration in Java

LinkedHashTable implementation in Java

Get the enumeration from a Collection

Get the enumeration from an Iterator in Java

Get a map from enum in Java

No comments:

Post a Comment