Get List<String> and HashMap<String, Object> using Java 8 streams

问题: 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 cl...

问题:

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:

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());
  • 发表于 2019-02-27 11:43
  • 阅读 ( 229 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除