Java – How to find an object based on the index of an integer array?

How to find an object based on the index of an integer array?… here is a solution to the problem.

How to find an object based on the index of an integer array?

I have an array of integers as such

Integer[] myArray= {1,3}; 

I have another list of objects, MyDept, which has the property id and name.

I want to get an object for MyDept whose ID matches the value of myArray.

If the object in the list is

Objfirst(1,"Training"), Objsecond(2,"Legal"), Objthird(3,"Media") 

Then I want Objfirst and Objthird.

Solution

You can do it in two steps:

List<MyDept> myDepts = new ArrayList<>();  initialised arraylist of your objects

 collect the objects into a Map based on their 'id's
Map<Integer, MyDept> myDeptMap = myDepts.stream().collect(Collectors.toMap(MyDept::getId, Function.identity()));

 iterate over the input array of 'id's and fetch the corresponding object to store in list
List<MyDept> myDeptList = Arrays.stream(myArray)
        .map(myDeptMap::get)
        .collect(Collectors.toList());

The minimum object is:

class MyDept{
    int id;
    String name;
     getters and setters
}

Related Problems and Solutions