jeudi 13 août 2015

Counting all elements in map of string to list

Is there a better way to calculate size of all lists in map? So firstList.size() + secondList().size? I have done this, but creating a list just for counting doesn't feel right approach ..

public static void main(String[] args) {
    List<String> firstList = new ArrayList<>();
    firstList.add("first");
    List<String> secondList = new ArrayList<>();
    secondList.add("second");

    Map<String, List<String>> myMap = new HashMap<>();
    myMap.put("one", firstList);
    myMap.put("two", secondList);

    int size = myMap.entrySet().stream().map(entry -> entry.getValue()).flatMap(list -> list.stream()).collect(Collectors.toList()).size();
    System.out.println("Size of all elements in map is:" + size);

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire