Finding the number of values ​​in a HashMap?

What is the best / most efficient way to find the total number of values ​​in a HashMap .

I do not mean the .size () method, since it counts the number of keys. I want the total number of values ​​in all keys.

I want to do this because my key is String , but my value is List .

+10
source share
7 answers

It would be simplest to repeat and add the list sizes.

 int total = 0; for (List<Foo> l : map.values()) { total += l.size(); } // here is the total values size 
+8
source

In Java 8, you can also use the Stream API:

 int total = map.values() .stream() .mapToInt(List::size) // or (l -> l.size()) .sum() 

This has the advantage that you do not need to repeat the List<Foo> for the for variable, as in pre-Java 8:

 int total = 0; for (List<Foo> list : map.values()) { total += list.size(); } System.out.println(total); 

In addition to this, although not recommended, you can also use this value in a string without the need for the temp variable:

 System.out.println(map.values().stream().mapToInt(List::size).sum()); 
+10
source

Say you have a card

 Map<String, List<Object>> map = new HashMap<>(); 

You can do this by calling the values() method and calling the size() method on all lists:

 int total = 0; Collection<List<Object>> listOfValues = map.values(); for (List<Object> oneList : listOfValues) { total += oneList.size(); } 
+3
source

If I understand the question correctly, you have Map<String, List<Something>> , and you want to calculate the total number of elements in all List in Map values. Java 8 offers a fairly simple way to do this, passing values, matching them with their size() , and then just summing them up:

 Map<String, List<Something>> map = ...; int totalSize = map.values().stream().mapToInt(List::size).sum()); 
+3
source

Starting with Java 8, given Map<K, List<V>> map you can use the Stream API and have:

 int size = map.values().stream().mapToInt(List::size).sum(); 

This creates Stream values ​​with stream() , maps each of them to their size with mapToInt , where mapper is a reference to the List::size method, referencing List#size() and summarize the results using sum() .

+3
source

With Eclipse Collections , the following will work using MutableMap .

 MutableMap<String, List<String>> map = Maps.mutable.of("key1", Lists.mutable.of("a", "b", "c"), "key2", Lists.mutable.of("d", "e", "f", "g")); long total = map.sumOfInt(List::size); 

Note. I am a committer for Eclipse collections.

+3
source
 import java.util.HashMap; public class Solution { public static void main(String args[]) { int total = 0; HashMap<String,String> a = new HashMap<String,String>(); a.put("1.","1"); a.put("2.","11"); a.put("3.","21"); a.put("4.","1211"); a.put("5.","111221"); for (String l : a.values()) { total ++; } System.out.println(total); } } 
0
source

Source: https://habr.com/ru/post/1245029/


All Articles