简体   繁体   中英

Get all elements in flat format from nested set structure

I need to get the data back similar to flatMap but it is not working in some scenario. Following are the details. Below is the pseudo code

class Employee {
 String name;
 int age;
}

Employee emp1 = new Employee("Peter",30);
Employee emp2 = new Employee("Bob",25);

Set<Employee> empSet1 = new HashSet();
empSet1.add(emp1);
empSet1.add(emp2);

Employee emp3 = new Employee("Jack",31);
Employee emp4 = new Employee("Laura",27);

Set<Employee> empSet2 = new HashSet();
empSet2.add(emp3);
empSet2.add(emp4);


Map<String,Set<Employee>> empLocationMap = new HashMap();

empLocationMap.put("location1",empSet1);
empLocationMap.put("location2",empSet2);


Set<Employee> empSet = getEmployeeSetForLocation("location1",empLocationMap);


private static Set getEmployeeSetForLocation(String location,Map<String,Set<Employee>> locationEmpMap) {
    Object filteredObject = locationMap.entrySet().stream().filter(element-> element.getKey().equals(location)).flatMap(element-> Stream.of(element)).collect(Collectors.toSet());
    
return new HashSet(filteredObject );
}

The filteredObject in the method getEmployeeSetForLocation on inspection shows containing 1 element and that element is of type Set containing 2 elements. I want to know, what modification can I make in the above logic to flatten the structure further so that filteredObject shows a set with 2 elements. Any pointers will be helpful. I am using Java 8.

Regards

Use flatMap, mapping the stream of MapEntry to stream of Employee

 Set<Employee> filteredObject = locationMap.entrySet().stream()
      -- Here you have stream of Map.Entry, where value is employee
      .filter(element -> element.getKey().equals(location)) 
      -- And here is how to convert this stream to Stream<Employee>
      .flatMap(s -> s.getValue().stream())
      .collect(Collectors.toSet());

Use Set::stream) in .flatMap() :

Object filteredObject = locationMap.entrySet().stream()
    .filter(entry -> entry.getKey().equals(location))
    .map(Map.Entry::getValue)
    .flatMap(Collection::stream)
    .collect(Collectors.toSet());

You already organized your employees by location in a map. Why are you going to the trouble to stream and filter the map when you already have access to the employees per location in the location map? Why not just do the following:

Set<Employee> set = empLocationMap.get("location1");

It gives the exact same result had you done the streaming and filtering. And since location is being used as a key you can only have one set of employees per location anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM