繁体   English   中英

如何在单个列表中添加多个值HashMap <Integer, ArrayList<User> &gt; map1 =新的HashMap <Integer, ArrayList<User> &gt;();

[英]How to add a multiple value in a single list HashMap<Integer, ArrayList<User>> map1 = new HashMap<Integer, ArrayList<User>>();

 HashMap<Integer, ArrayList<User>> map1 = new HashMap<Integer, ArrayList<User>>(); 

现在,假设Integer为101,并且该数组的值在[jan,10,200,city]中。 这样,如果我显示我的列表,它将像

101 :[jan,10,200,city]. 

如果我添加另一个它将像

101 :[jan,10,200,city].
102:[prav,103,2023,city]. 

但是这些东西要在运行时添加

查看put函数: Oracle文档-HashMap-Put

举例来说,假设您有一个

ArrayList<User> aList = new ArrayList<User>();

您可以将此列表设置为所需的任何内容,然后执行

map1.put(101, aList);

注意:我认为您的意思是创建一个

HashMap<Integer, User>();

因为您的整数键仅指向一个具有多个属性(日期,城市等)的用户。 在这种情况下,put的第二个参数将是User而不是ArrayList。

希望这可以帮助。 (对不起,格式不好,这是我的第一个答案)

代码如下将userList添加到Map

   package com.orm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

class User {
User(String name, int id, String city) {
    this.name = name;
    this.id = id;
    this.city = city;
}

String name;
int id;
String city;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

}

  public class Main {

public static void main(String[] args) {
     Map<Integer ,ArrayList<User> > userMap = new HashMap<Integer, ArrayList<User>>();
     User user1 = new User("Jan", 101, "city");
     User user2 = new User("Prav", 103, "city");
     ArrayList<User>userList = new ArrayList<User>();
     userList.add(user1);
     userList.add(user2);
     userMap.put(1,userList )
        }

}

暂无
暂无

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

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