'How to add Map<String,String> in Collection<Map<String,String>> [closed]

I want to add Map<String,String> to a Collection<Map<String,String>> can anyone guide me how we can do this ?



Solution 1:[1]

All you have to do is use Collection.add() like you would with any other collection item. There isn't anything truly different between adding a String to an ArrayList and adding a Map to another type of Collection. The thing that's probably throwing you off is the extra angle brackets (<>). However, you do need to choose a type of Collection to declare. You can't really just declare a new Collection<>(). I'd recommend either an ArrayList or a HashSet.

Either declare a map first then add it to the collection:

Map<String, String> map = new HashMap<>();
Collection<Map<String, String>> collection = new HashSet<>();
collection.add(map);

Or just declare it once you want to add it:

Collection<Map<String, String>> collection = new HashSet<>();
collection.add(new HashMap<>());

P.S. Don't forget to import everything:

import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ilanfriedman