Counting all elements in map of string to list

99封情书 提交于 2020-08-05 07:23:05

问题


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);
}

回答1:


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() :]




回答2:


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();



回答3:


Another way:

private static int size = 0;

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);

    myMap.values().forEach(value -> {size += value.size();});
    System.out.println("Size of all elements in map is:" + size); 
}


来源:https://stackoverflow.com/questions/32000111/counting-all-elements-in-map-of-string-to-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!