I would recommend you do it as follows:
- first stream the
addressList to create an address map which has the pid as the key and the address as the value.
- then stream the
personList, mapping to the id and filtering on the existence of that id in the address map.
This has two advantages.
- The contents of
personList and addressList may be in any order.
- Only those ids in
personList will be used, ignoring any other ids in the addressList. So the lists are not required to be one-to-one or even the same size.
First, I used two records (classes would also work exactly the same way) to house some data. For this demo, only the pertinent information is included.
record Person(String getPid) {
};
record Address(String getPid, String getLocation) {
};
Next, I create lists with the test data. Both lists will contain id's not in the other.
List<Person> personList = List.of(new Person("id1"),
new Person("id2"), new Person("id3"), new Person("id6"));
List<Address> addressList =
List.of(new Address("id3", "Utah"),
new Address("id1", "Idaho"),
new Address("id2", "Virginia"),
new Address("id5", "New York"));
Now create a map of pid to address. If two addresses exist for the same id, only the first encountered is used.
Map<String, Address> addressMap =
addressList.stream().collect(Collectors
.toMap(Address::getPid, address -> address,
(ad1,ad2)->ad1));
Now create the final map.
- stream the
personList and pull out the ids
- now filter to ensure the given id is in the
address map.
- and enter the id and the location for given id in the map
Map<String, String> result = personList.stream()
.map(Person::getPid).filter(addressMap::containsKey)
.collect(Collectors.toMap(id -> id,
id -> addressMap.get(id).getLocation));
result.entrySet().forEach(System.out::println);
For the test data, the following is printed.
id2=Virginia
id1=Idaho
id3=Utah
Person,Addressobjects for reference?pid's are the same ID for the address or the person?