1

Here is something similar which I am working on my project. Classes are different for an obvious reason. Let's just say I have class

public class Division {
    String className;
    Map<String, Student> studentMap;
    // getters and setters      
}

and

public class Student {
    String fName;
    String lName;
    String id;
    // getters and setters
}

and I have instances for these classes as below:

Student s1= new Student("Lisa", "xyz", "12");
Student s2= new Student("John", "klm", "13");
Student s3= new Student("Lisa", "xyz", "14");

Division d1= new Division();
Division d2= new Division();

Map<String, Student> studentMap1= new HashMap<>();
studentMap1.put("key1", s1);
studentMap1.put("key2", s2);

Map<String, Student> studentMap2= new HashMap<>();
studentMap2.put("key3", s3);


d1.setStudentMap(studentMap1);
d2.setStudentMap(studentMap2);

List<Division> dList= Arrays.asList(d1, d2);

Here, note that keys that we are using in HashMap are unique across db. so I can write something like this in Java 7 to get all the studentMap

  1. Get all students Map

    Map<String, Student> allstudentsMap= new HashMap<>();
    
    for(Division d: dList) {
    
        for(String key:d.getStudentMap().keySet()) {
            allstudentsMap.put(key, d.getStudentMap().get(key));
    
        }
    }
    
  2. I need to also get list of keys for some filter condition. eg get keys list for students with name Lisa. I can get get a list using above HashMap as below:

    List<String> filterList= new ArrayList<>();
    Student s;
    for(String key:allstudentsMap.keySet()) {
    
        s= allstudentsMap.get(key);
        if(s.getfName().equalsIgnoreCase("Lisa")) {
            filterList.add(key);
        }
    
    }
    

I need a help to do same thing using Java 8 streams. 1. Get all students Map 2. Get List of all keys for some filter condition.

1 Answer 1

3

Considering all keys are unique across, you could simply put every entry from several maps into your final map as:

Map<String, Student> allStudentsMap = new HashMap<>();
dList.forEach(d -> d.getStudentMap().forEach(allStudentsMap::put));

and further, apply the filter on the entrySet and collect corresponding keys :

List<String> filterList = allStudentsMap.entrySet().stream()
        .filter(e -> e.getValue().getfName().equalsIgnoreCase("Lisa"))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

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.