C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Put: This adds a key-value pair to the ListMultimap. We can call put on the same key more than once with no error.
Get: This retrieves a list of all the values located at this key. We can loop over this with for.
ForContainsKey: This tells us whether a key exists or not in the map. It returns true for "dog" in this program.
Java program that uses ListMultimap
import java.util.List;
import com.google.common.collect.*;
public class Program {
public static void main(String[] args) {
// Create a map to ArrayList values.
ListMultimap<String, Integer> map = ArrayListMultimap.create();
// Add pairs to ListMultimap.
map.put("cat", 5);
map.put("dog", 10);
map.put("cat", 20);
// Get list at this key.
// ... Iterate over its values.
List<Integer> list = map.get("cat");
for (int value : list) {
System.out.println(value);
}
// See if ListMultimap contains this key.
if (map.containsKey("dog")) {
System.out.println(true);
}
}
}
Output
5
20
true
Here: We add three values to the key "sky." We then remove one, the value 20. The other two values still exist at the key.
Java program that uses remove
import com.google.common.collect.*;
public class Program {
public static void main(String[] args) {
// Create a ListMultimap and add data to it.
ListMultimap<String, Integer> map = ArrayListMultimap.create();
map.put("lawn", 10);
map.put("sky", 50); // Add three values at sky.
map.put("sky", 20);
map.put("sky", 100);
// Remove one of the values at sky.
map.remove("sky", 20);
// Sky now has just two values.
System.out.println(map);
}
}
Output
{sky=[50, 100], lawn=[10]}
Tip: To see if a key exists, please use containsKey. This makes code clearer and easier to understand.
Java program that gets nonexistent key
import java.util.List;
import com.google.common.collect.*;
public class Program {
public static void main(String[] args) {
// Create an empty ListMultimap.
ListMultimap<String, Integer> map = ArrayListMultimap.create();
// It is empty.
System.out.println(map.isEmpty());
// Remove one of the values at sky.
List<Integer> list = map.get("Hyperion");
// A nonexistent value list is empty, not null.
System.out.println(list);
System.out.println(list.isEmpty());
System.out.println(list.size());
}
}
Output
true
[]
true
0