How to add element into ArrayList in HashMap

前端 未结 5 756
予麋鹿
予麋鹿 2020-12-15 05:22

How to add element into ArrayList in HashMap?

    HashMap> Items = new HashMap>();


        
相关标签:
5条回答
  • 2020-12-15 06:00

    Typical code is to create an explicit method to add to the list, and create the ArrayList on the fly when adding. Note the synchronization so the list only gets created once!

    @Override
    public synchronized boolean addToList(String key, Item item) {
       Collection<Item> list = theMap.get(key);
       if (list == null)  {
          list = new ArrayList<Item>();  // or, if you prefer, some other List, a Set, etc...
          theMap.put(key, list );
       }
    
       return list.add(item);
    }
    
    0 讨论(0)
  • 2020-12-15 06:17

    First you have to add an ArrayList to the Map

    ArrayList<Item> al = new ArrayList<Item>();
    
    Items.add("theKey", al); 
    

    then you can add an item to the ArrayLIst that is inside the Map like this:

    Items.get("theKey").add(item);  // item is an object of type Item
    
    0 讨论(0)
  • 2020-12-15 06:17
    #i'm also maintaining insertion order here
    Map<Integer,ArrayList> d=new LinkedHashMap<>();
    for( int i=0; i<2; i++)
    {
    int id=s.nextInt();
    ArrayList al=new ArrayList<>();
    al.add(s.next());  //name
    al.add(s.next());  //category
    al.add(s.nextInt()); //fee
    d.put(id, al);
     }
    
    0 讨论(0)
  • 2020-12-15 06:18

    I know, this is an old question. But just for the sake of completeness, the lambda version.

    Map<String, List<Item>> items = new HashMap<>();
    items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);
    
    0 讨论(0)
  • 2020-12-15 06:22
    HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();
    
    public synchronized void addToList(String mapKey, Item myItem) {
        List<Item> itemsList = items.get(mapKey);
    
        // if list does not exist create it
        if(itemsList == null) {
             itemsList = new ArrayList<Item>();
             itemsList.add(myItem);
             items.put(mapKey, itemsList);
        } else {
            // add if item is not already in list
            if(!itemsList.contains(myItem)) itemsList.add(myItem);
        }
    }
    
    0 讨论(0)
提交回复
热议问题