I have few person objects and a function to select the person for the given entity id:
person1 = {
name = "abc";
id = "1";
}
person2 = {
name = "xyz";
id = "2";
}
person3 = {
name = "aaa";
id = null;
}
Person getPersonFunction(List<Person> persons, String id) {
//Get the person for the given id and if id is not for any person from the list then select the person with null as id.
}
Here is the problem: I want to select the person for a given entity id and if there is no such person present in the list for the given entity id then select the person whose entity id is set to null. These will be always one person whose entity id is set to null and it's like a default person. I can solve this problem with easily by using for loop but I want to solve this problem using java stream. Here is what I did:
Map<String, Person> personMap = persons.stream().collect(Collectors.toMap(Person::id, person -> person);
Person person = personMap.getOrDefault(id, personMap.get(null))
This gives me the correct result but I want to do it in a single line.
id? Just search linearly.O(n)steps. Then in case he doesn't find its element he will use the map for kind of O(1) steps to find the element withid==null