Get all elements in flat format from nested set structure

Tags:



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

Answer

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());


Source: stackoverflow