簡體   English   中英

將字符串數組轉換為Map

[英]Converting string arrays into Map

我有兩個字符串數組鍵和值

String[] keys = {a,b,c,d};

String[] values = {1,2,3,4};

將它們轉換為地圖的最快方法是什么? 我知道我們可以遍歷它們。 但是,有沒有任何實用工具?

比這更快?

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

if(keys.length == values.length){
    for(int index = 0; index < keys.length; index++){
        map.put(keys[index], values[index]);
    }
}

恕我直言,你不太可能找到這樣的實用工具。

但是,即使你發現一個機會真的很低,它也會提供任何性能提升。 因為,我認為如果不迭代兩個數組中的所有元素,你將無法做到這一點。

我可以建議的一件事是(只有你的數組有大量的元素),你可以指定地圖的容量,同時實例化它,以減少調整大小時的開銷。

Map<String, String> map = new HashMap<String, String>(keys.length);
//put keys and values into map ...

從一開始就進行恆定時間查找

如果您正在尋找一個Map,它可以在恆定時間內檢索與鍵相關聯的值(意味着無需查看大多數值),那么您無法做得更快,因為需要處理數組。

但是,您可以使用已編寫的實用程序: com.google.common.collect.Maps.uniqueIndex

瞬時轉換,線性時間查找

如果你沒有使用Map每次都在數組中搜索鍵,那么你可以使用你的兩個數組立即創建Map,方法是定義一個實現Map接口的新類:

class TwoArrayMap implements Map<String, String> {

   private final String[] keys;
   private final String[] values;
   // If you want to enable to add more key value pairs to your map, and
   // want to make the process faster, you could use ArrayLists instead of arrays

   public TwoArrayMap(String[] array1, String[] array2){
       if(array1 == null || array2 == null || array2.length < array1.length)
          throw new IllegalArgumentException();
       keys = array1;
       values = array2;
       // Alternatively, you could want to clone the arrays, to 
       // make sure they are not modified, using array1.clone(), etc
   }

   public String get(String key){

       for(int i=0; i<keys.length; i++)
             if(key == null && key == null || key != null && key.equals(k) )
                return values[i];
       return null;                     
   }

   public String put(String key, String Value) throws OperationNotSupportedException {
        throw new OperationNotSupportedException();
        // alternatively, you could resize the arrays and add a new key, or use an ArrayList
   }

}

Map<String, String> myMap = new TwoArrayMap(keys, values);


延遲轉換,轉換后的恆定時間查找

另一種方法是“懶惰”地執行它,意思是修改上面的類,以便它在內部保持對HashMap的引用,並且只在查找元素時填充它:

class TwoArrayMap implements Map<String, String> {

   private final Map<String, String> hashmap;
   private int maxIndexAlreadyTransferred = -1;

   private final String[] keys;
   private final String[] values;

   public TwoArrayMap(String[] array1, String[] array2){
       if(array1 == null || array2 == null || array2.length < array1.length)
          throw new IllegalArgumentException();
       hashmap = new HashMap<>();
       keys = array1;
       values = array2;
       // Alternatively, you could want to clone the arrays, to 
       // make sure they are not modified, using array1.clone(), etc
   }

   public String get(String key){

       if(hashmap.containsKey(key))
            return hashmap.get(key);

       String k, value;
       while( maxIndexAlreadyTransferred + 1 < keys.length ){
             k = keys[ maxIndexAlreadyTransferred + 1 ];
             value = values[ maxIndexAlreadyTransferred +1 ];
             if(!hashmap.containsKey(k))
                 hashmap.put( k, value );
             maxIndexAlreadyTransferred++;
             if(key == null && k == null || key != null && key.equals(k) )
                return value;
       }
       return null;                     
   }

   public String put(String key, String Value) {
        hashmap.put(key, value);
   }

}

這個解決方案意味着:

  • 即時創建新對象
  • 線性時間查找,您將查詢它的第一次,直到所有內容都被傳輸
  • 之后的常量時間查找,表現為哈希表

我的目的是兩個非常簡單的實現。 一個是Java 8的流Api,一個沒有。

Java <8 (沒有流api)

if(keys.length != values.length) { 
    throw new IllegalArgumentException("Keys and Values need to have the same length."); 
}
Map<String,String> map = new HashMap<>();
for (int i = 0; i < keys.length; i++) {
    map.put(keys[i], values[i]);
}

Java> 8 (帶流api)

if(keys.length != values.length) { 
    throw new IllegalArgumentException("Keys and Values need to have the same length."); 
}
Map<String,String> map = IntStream.range(0, keys.length).boxed()
    .collect(Collectors.toMap(i -> keys[i], i -> values[i]));

將兩個String數組轉換為Java中的Map

import java.util.HashMap;
 public static void main(String[] args){
    String[] keys= {"a", "b", "c"};
    int[] vals= {1, 2, 3};
    HashMap<String, Integer> hash= new HashMap<String, Integer>();

    for(int i= 0; i < keys.length; i++){
      hash.put(keys[i], vals[i]);
    }
 }

查看此LINK以獲取更多不同編程語言的解決方案

Note :鍵應該是唯一的..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM