Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a hashmap of the following type

HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();    

The values stored are like this :

mango | 0,4,8,9,12
apple | 2,3
grapes| 1,7
peach | 5,6,11

I want to store as well as fetch those Integers using Iterator or any other way with minimum lines of code.How can I do it?

EDIT 1

The numbers are added at random (not together) as key is matched to the appropriate line.

EDIT 2

How can I point to the arraylist while adding ?

I am getting error while adding a new number 18 in the line map.put(string,number);

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

Our variable:

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

To store:

map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

To add numbers one and one, you can do something like this:

String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);

In Java 8 you can use putIfAbsent to add the list if it did not exist already:

map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);

Use the map.entrySet() method to iterate on:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...