John
John

Reputation: 750

How to find objects based on index of Integer array?

I have an Integer array as

Integer[] myArray= {1,3}; 

I have another List of objects MyDept which has the properties id and name.

I want to get those objects of MyDept whose ids matches with the values of myArray.

If the objects in the list are

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

then I want Objfirst and Objthird.

Upvotes: 3

Views: 48

Answers (1)

Naman
Naman

Reputation: 31888

You can do it in two steps as :

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());

with a minimal object as :

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

Upvotes: 3

Related Questions