I'm still a beginner of Java 8. I'm getting stuck on filtering a Map of List values. Here is my code
public class MapFilterList {
private static Map<String, List<Person>> personMap = new HashMap<>();
public static void main(String[] args) {
Person p1 = new Person("John", 22);
Person p2 = new Person("Smith", 45);
Person p3 = new Person("Sarah", 27);
List<Person> group1 = new ArrayList<>();
group1.add(p1);
group1.add(p2);
List<Person> group2 = new ArrayList<>();
group2.add(p2);
group2.add(p3);
List<Person> group3 = new ArrayList<>();
group3.add(p3);
group3.add(p1);
personMap.put("group1", group1);
personMap.put("group2", group2);
personMap.put("group3", group3);
doFilter("group1").forEach(person -> {
System.out.println(person.getName() + " -- " + person.getAge());
});
}
public static List<Person> doFilter(String groupName) {
return personMap.entrySet().stream().filter(key -> key.equals(groupName)).map(map -> map.getValue()).collect(Collectors.toList());
}
}
How can I make to correct doFilter method because the error show me cannot convert from List<List<Person>> to List<Person>.
personMap.get(groupName)? As I understand,doFiltershould do exactly this job.personMap.get(groupName)or, if collecting into a new list really is required, still as simple asnew ArrayList<>(personMap.get(groupName))…getis for), using a predicate that is known to have exactly one match implies that you could usefindFirstor similar to get the particularList. Collecting into a new list is only necessary, if you know that you will have to merge multiple lists into one.