简体   繁体   English

从 hashmap 存储和检索 ArrayList 值

[英]Storing and Retrieving ArrayList values from hashmap

I have a hashmap of the following type我有以下类型的 hashmap

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编辑 1

The numbers are added at random (not together) as key is matched to the appropriate line.这些数字是随机添加的(不是一起添加的),因为密钥与相应的行匹配。

EDIT 2编辑 2

How can I point to the arraylist while adding?添加时如何指向 arraylist?

I am getting error while adding a new number 18 in the line map.put(string,number);map.put(string,number);行中添加新数字18时出现错误

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:在 Java 8 中,如果列表不存在,您可以使用putIfAbsent添加列表:

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

Use the map.entrySet() method to iterate on:使用map.entrySet()方法迭代:

for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
     Map.Entry pairs = (Map.Entry)it.next();

     if(pairs.getKey().equals("mango"))
     {
        map.put(pairs.getKey(), pairs.getValue().add(18));
     }

     else if(!map.containsKey("mango"))
     {
        List<Integer> ints = new ArrayList<Integer>();
        ints.add(18);
        map.put("mango",ints);
     }

     it.remove(); // avoids a ConcurrentModificationException
}

EDIT: So inside the while try this:编辑:所以在里面试试这个:

map.put(pairs.getKey(), pairs.getValue().add(number))

You are getting the error because you are trying to put an integer to the values, whereas it is expected an ArrayList .您收到错误是因为您试图将整数放入值中,而预期为ArrayList

EDIT 2: Then put the following inside your while loop:编辑 2:然后将以下内容放入您的 while 循环中:

if(pairs.getKey().equals("mango"))
{
    map.put(pairs.getKey(), pairs.getValue().add(18));
}

else if(!map.containsKey("mango"))
{
     List<Integer> ints = new ArrayList<Integer>();
     ints.add(18);
     map.put("mango",ints);
 }

EDIT 3: By reading your requirements, I come to think you may not need a loop.编辑 3:通过阅读您的要求,我开始认为您可能不需要循环。 You may want to only check if the map contains the key mango , and if it does add 18 , else create a new entry in the map with key mango and value 18 .您可能只想检查映射是否包含键mango ,如果确实添加了18 ,则在映射中创建一个键为mango且值为18的新条目。

So all you may need is the following, without the loop:所以你可能需要的是以下内容,没有循环:

if(map.containsKey("mango"))
{
    map.put("mango", map.get("mango).add(18));
}

else
{
    List<Integer> ints = new ArrayList<Integer>();
    ints.add(18);
    map.put("mango", ints);
}

You can use like this(Though the random number generator logic is not upto the mark)你可以这样使用(虽然随机数生成器逻辑不符合标准)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

OUTPUT输出

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

You could try using MultiMap instead of HashMap您可以尝试使用 MultiMap 而不是 HashMap

Initialising it will require fewer lines of codes.初始化它需要更少的代码行。 Adding and retrieving the values will also make it shorter.添加和检索值也会使其更短。

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

would become:会变成:

Multimap<String, Integer> multiMap = ArrayListMultimap.create();

You can check this link:http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and您可以查看此链接:http ://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and

for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
 System.out.println( entry.getKey());     
 System.out.println( entry.getValue());//Returns the list of values
}

The modern way (as of 2020) to add entries to a multimap (a map of lists) in Java is:在 Java 中向多映射(列表映射)添加条目的现代方法(截至 2020 年)是:

map.computeIfAbsent("apple", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("apple", k -> new ArrayList<>()).add(3);

According to Map.computeIfAbsent docs:根据Map.computeIfAbsent文档:

If the specified key is not already associated with a value (or is mapped to null ), attempts to compute its value using the given mapping function and enters it into this map unless null .如果指定的键尚未与值关联(或映射到null ),则尝试使用给定的映射函数计算其值并将其输入此映射,除非null

Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null返回: the current (existing or computed) value associated with the specified key, or null if the computed value is null

The most idiomatic way to iterate a map of lists is using Map.forEach and Iterable.forEach :迭代列表映射最惯用的方法是使用Map.forEachIterable.forEach

map.forEach((k, l) -> l.forEach(v -> /* use k and v here */));

Or, as shown in other answers, a traditional for loop:或者,如其他答案所示,传统的for循环:

for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
    String k = e.getKey();
    for (Integer v : e.getValue()) {
        /* use k and v here */
    }
}

Method1 : Use putIfAbsent方法 1:使用 putIfAbsent

    Map<String, List<Integer>> map = new HashMap();
    map.putIfAbsent("mango",new ArrayList<>());
    map.get("mango").add(5);

Method 2: Check key present in Map方法 2:检查 Map 中存在的密钥

    Map<String, List<Integer>> map = new HashMap();
    if(! map.containsKey("mango"){
          map.put("mango",new ArrayList<>());
    }
    List<Integer> list = map.get("mango");
    list.add(3);
  
    

Method 3: Use getOrDefault方法 3:使用 getOrDefault

    Map<String, List<Integer>> map = new HashMap();
    List<Integer> list = map.getOrDefault("mango",new ArrayList<>());
    list.add(4)

      
  
static HashMap<Integer, ArrayList<Integer>> has(int arr[], int target) {
    HashMap<Integer, ArrayList<Integer>> hm = new HashMap<Integer, ArrayList<Integer>>();
    for (int i = 0; i < arr.length; i++) {
        if (!hm.containsKey(arr[i])) {
            ArrayList<Integer> res = new ArrayList<Integer>();
            res.add(i + 1);
            hm.put(arr[i], res);
        } else {
            hm.get(arr[i]).add(i);
        }
    }
    return hm;
}

Fetch all at once =一次获取所有=

List<Integer> list = null;

if(map!= null) 
{ 
  list = new ArrayList<Integer>(map.values()); 
}

For Storing =用于存储 =

if(map!= null) 
{ 
  list = map.get(keyString); 
   if(list == null)
    {
         list = new ArrayList<Integer>();
    }
  list.add(value);
  map.put(keyString,list);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM