3

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.

1
  • 3
    what have you tried so far? Commented Dec 6, 2018 at 6:09

1 Answer 1

3

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is passing the index to myDeptMap.get, correct? I think you should pass the element at that index instead, i.e. I wouldn't use a range. Instead, I would just stream the array.
@FedericoPeraltaSchaffner yes makes sense, updated. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.