Skip to content
Advertisement

Compare Map Value with list using Stream API

Need to collect the common value from a List of String and from a MAP having String as KEY and List as VALUE.

Snippet:

public Map<String, List> maping() throws Exception {

String id="test";

List<String> no = new ArrayList<String>();

no.add("123456");
no.add("654321");
no.add("11223344");

Map<String, List> info = new HashMap<String, List>();
info .put(id, no);

return info ;
}

    public List getInfo() {
    
    List<String> listNo = new ArrayList<String>();
    listNo.add("123456");
    listNo.add("654321");
    listNo.add("135790");
    listNo.add("123987");
    listNo.add("11223344");
    return listNo;
    
}

In third method need to compare the List and MAP value and collect the common no in a List. Please guide using JAVA 8 Stream API

Advertisement

Answer

public List<String> collectCommonNumbers(Map<String, List<String>> inputMap, List<String> inputList) {
  return inputMap.values().stream().flatMap(List::stream).distinct().filter(inputList::contains).collect(Collectors.toList());
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement