Best way to create a hashmap of arraylist

后端 未结 9 1008
小鲜肉
小鲜肉 2020-11-27 05:35

I have one million rows of data in .txt format. the format is very simple. For each row:

user1,value1
user2,value2
user3,value3
user1,value4
...

You k

相关标签:
9条回答
  • 2020-11-27 06:36

    Since Java 8 you can use map.computeIfAbsent

    https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-

    Collection<String> values = map.computeIfAbsent(user, k -> new ArrayList<>());
    values.add(value);
    
    0 讨论(0)
  • 2020-11-27 06:38

    I Could not find any easy way. MultiMap is not always an option available. So I wrote something this.

    public class Context<K, V> extends HashMap<K, V> {
    
        public V addMulti(K paramK, V paramV) {
            V value = get(paramK);
            if (value == null) {
                List<V> list = new ArrayList<V>();
                list.add(paramV);
                put(paramK, paramV);
            } else if (value instanceof List<?>) {
                ((List<V>)value).add(paramV);
            } else {
                List<V> list = new ArrayList<V>();
                list.add(value);
                list.add(paramV);
                put(paramK, (V) list);
            }
            return paramV;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 06:40

    If you don't want to import a library.

    package util;    
    
    import java.util.ArrayList;    
    import java.util.HashMap;    
    import java.util.List;    
    
    /**    
     * A simple implementation of a MultiMap. This implementation allows duplicate elements in the the    
     * values. (I know classes like this are out there but the ones available to me didn't work).    
     */    
    public class MultiMap<K, V> extends HashMap<K, List<V>> {    
    
      /**    
       * Looks for a list that is mapped to the given key. If there is not one then a new one is created    
       * mapped and has the value added to it.    
       *     
       * @param key    
       * @param value    
       * @return true if the list has already been created, false if a new list is created.    
       */    
      public boolean putOne(K key, V value) {    
        if (this.containsKey(key)) {    
          this.get(key).add(value);    
          return true;    
        } else {    
          List<V> values = new ArrayList<>();    
          values.add(value);    
          this.put(key, values);    
          return false;    
        }    
      }    
    }    
    
    0 讨论(0)
提交回复
热议问题