简体   繁体   中英

selecting map based on values in the list

I have listofMaps and listOfStrings. How can I get only those maps in resultant list with values matching in the listofstring?

List<Map<String, Object>> list = listofMaps
                                 .stream()
                                 .filter(maps -> maps.containsValue(listOfString))
                                 .collect(Collectors.toList());

if I replace listOfString with actual string like "string" then one map gets selected but not the multiple matching maps.

If a value in the map is matched to any possible value in the listOfStrings , anyMatch needs to be used along with List::contains :

List<Map<String, Object>> listofMaps = Arrays.asList(
    Map.of("id", 1, "name", "abc"),
    Map.of("id", 2, "name", "xyz"),
    Map.of("id", 3, "name", "stu")
);

List<String> listOfString = Arrays.asList("abc", "stu");

List<Map<String, Object>> listAnyMatch = listofMaps
        .stream()
        .filter(maps -> maps.values()
                            .stream()
                            .anyMatch(listOfString::contains))
        .collect(Collectors.toList());

listAnyMatch.forEach(System.out::println);

Output

{name=abc, id=1}
{name=stu, id=3}

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