Reputation: 39
I'm new to Java and I'm struggling to figure out something trivial.
I have a HashMap
with keys of type String
and values of type ArrayList <String>
, and it returns something like this:
dict = {Color=[Blue, Purple]}
I'm struggling to figure out how I can grab a specific element from the array in the value of dict. Like if I got dict.value[0]
, it would return the string 'Blue'.
I've tried doing:
Object values = dict.values().toArray[0];
and I assumed that since I changed it to an array, I could do something like values.get(0)
to get the first element, but that doesn't work because values is type Object
. Any ideas on how to resolve this?
Upvotes: 2
Views: 1291
Reputation: 723
Cast to type of java.util.List
, and then you can get value through index.
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>(2);
map.put("color", Arrays.asList("blue", "yellow", "green", "white"));
map.put("size", Arrays.asList("small", "medium", "large"));
List<String> o = (List<String>) map.values().toArray()[0];
System.out.println(o.get(0)); //output is 'blue'
List<String> s = (List<String>) map.values().toArray()[1];
System.out.println(s.get(1)); //output is 'medium'
}
Upvotes: 0
Reputation: 18430
First, use .get()
on map to get the ArrayList using key
List<String> colors = dict.get("Color");
Then use .get()
on list to get the element using index
String color = colors.get(0);
You can do this in one line this way
String color = dict.get("Color").get(0);
You are trying with dict.values().toArray[0]
which is wrong syntax thats the problem. dict.values()
will return Collection<List<String>>
, you can get List of values this way
List<List<String>> listOfValues = new ArrayList<>(colorsMap.values());
Then you can access each value by index using .get()
List<String> colors = listOfValues.get(0);
Note : HashMap don't store any order.
Upvotes: 0
Reputation: 1675
if your HashMap
is like:
Map<String, List<String>> myColorsMap = new HashMap<>();
And after populating the map is like:
{Red=[firstRed, secondRed, thirdRed], Blue=[firstBlue, secondBlue, thirdBlue]}
then you can retrieve Blue's key value (a List
) like:
String blueFirstElement = myColorsMap.get("Blue").get(0); // --> will give first element of List<String> stored against Blue key.
To get collection of all keys in your map (or "dictionary"):
myColorsMap.keySet();
will give:
[Red, Blue]
When you do:
Object values = dict.values().toArray[0];
First, this is wrong. What you were trying to do is this:
Object values = dict.values().toArray();
Which returns Object[]
and it is ambiguous. No need to do that. Java's Map
interface and HashMap
implementation have a lot of utility methods for you to iterate and retrieve your values.
Upvotes: 3