Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 220
Sagar Avatar asked Nov 16 '25 09:11

Sagar


2 Answers

This is at least more readable

int size = myMap.values().stream()
     .mapToInt(Collection::size)
     .sum();

or if you want to look like a functional programming guru, use:

int size2 = myMap.values().stream()
     .reduce(0, (acc, val) -> acc + val.size(), Integer::sum);

EDIT: using the .values() :]

like image 99
Jiri Kremser Avatar answered Nov 18 '25 06:11

Jiri Kremser


Both of the previous answers are good, but can be shortened a bit more by going straight for the values(), rather than iterating the entrySet():

// Streaming version
int size = myMap.values().stream()
     .mapToInt(list -> list.size())
     .sum();

// Standard loop version
int size = 0;
for (List<String> list : myMap.values())
    size += list.size();
like image 25
Andreas Avatar answered Nov 18 '25 05:11

Andreas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!