# Q：计算字符串列表中所有元素的列表

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<>();
List<String> secondList = new ArrayList<>();

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

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<>();
List<String> secondList = new ArrayList<>();

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

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

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

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

EDIT: using the `.values()` :]

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

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

Another way:

``````private static int size = 0;

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

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

``````private static int size = 0;

public static void main(String[] args) {
List<String> firstList = new ArrayList<>();