Create a map from two different lists based on common conditions using Java 8 Streams

  • A+

I have two list instances like this:

List<NameAndAge> nameAndAgeList = new ArrayList<>(); nameAndAgeList.add(new NameAndAge("John", "28")); nameAndAgeList.add(new NameAndAge("Paul", "30")); nameAndAgeList.add(new NameAndAge("Adam", "31"));  List<NameAndSalary> nameAndSalaryList = new ArrayList<>(); nameAndSalaryList.add(new NameAndSalary("John", 1000)); nameAndSalaryList.add(new NameAndSalary("Paul", 1100)); nameAndSalaryList.add(new NameAndSalary("Adam", 1200)); 

where NameAndAge is

class NameAndAge {     public String name;     public String age;      public NameAndAge(String name, String age) { = name;         this.age = age;     }      @Override     public String toString() {         return name + ": " + age;     } } 

and NameAndSalary is

private class NameAndSalary {     private String name;     private double salary;      public NameAndSalary(String name, double salary) { = name;         this.salary = salary;     }      @Override     public String toString() {         return name + ": " + salary;     } } 

Now, I want to create a map with key as NameAndAge object from the first list and value as NameAndSalary from the second list where the name is equal in both the objects.

So, when I print the map, it should look like this:

{John: 28=John: 1000.0} {Paul: 30=Paul: 1100.0} {Adam: 31=Adam: 1200.0} 

I have tried doing this, but the end return type is 'void' so I'm stuck clueless as I am new to Streams.

nameAndAgeList     .forEach(n ->         nameAndSalaryList             .stream()             .filter(ns ->             .collect(Collectors.toList())); 

Can someone please advise how can this be achieved with Java Streams API?


This should do the trick, too:

Map<NameAndAge, NameAndSalary> map = new HashMap<>(); nameAndAgeList.forEach(age -> {      NameAndSalary salary =               s -> age.getName().equals(s.getName())).               findFirst().               orElseThrow(IllegalStateException::new);       map.put(age, salary); }); 

Mind that it would throw an IllegalStateException if a matching name can't be found.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: