java 将字符串数组转换为 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12418334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:49:07  来源:igfitidea点击:

Converting string arrays into Map

javaarrayshashmap

提问by user2434

I have two string arrays keys and values

我有两个字符串数组键和值

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

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

What is the fastest way to convert them into a map? I know we can iterate through them. But, is there any utility present?

将它们转换为地图的最快方法是什么?我知道我们可以遍历它们。但是,有任何实用程序吗?

回答by Sujay

Faster than this?

比这还快?

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]);
    }
}

回答by Vic Seedoubleyew

Constant time lookup from the start

从一开始的恒定时间查找

If you are looking for a Map that retrieves the value associated with a key in constant time (meaning without having to look at most values), then you cannot do much faster, because the arrays need to be processed.

如果您正在寻找一个 Map 以恒定时间检索与键关联的值(意味着不必查看大多数值),那么您不能做得更快,因为需要处理数组。

However, you can use a utility already written that way : com.google.common.collect.Maps.uniqueIndex

但是,您可以使用已经这样编写的实用程序: com.google.common.collect.Maps.uniqueIndex

Instantaneous conversion, Linear time lookup

瞬时转换,线性时间查找

If you are ok with a Map that searches the array for the key every time, then you can create the Map instantly using your two arrays, by defining a new class that implements the Map interface :

如果您对每次都在数组中搜索键的 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);



Lazy conversion, constant time lookup after conversion

懒惰转换,转换后恒定时间查找

Another approach would be to do it "lazily", meaning modify the above class, so that it keeps a reference to a HashMap internally, and fills it only when it is looking up elements :

另一种方法是“懒惰”地执行它,这意味着修改上面的类,以便它在内部保留对 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);
   }

}

This solution would mean :

这个解决方案意味着:

  • an instantaneous creation of your new object
  • linear time lookup for the first times you will query it, until everything is transferred
  • constant time lookup after that, behaving as a hash table
  • 即时创建您的新对象
  • 线性时间查找第一次你会查询它,直到一切都被转移
  • 之后的恒定时间查找,表现为哈希表

回答by Valentin Michalak

I purpose to you two very simple implementations. One with stream Api of Java 8, one without.

我的目的是给你两个非常简单的实现。一种带有 Java 8 的流 Api,一种没有。

Java < 8 (without stream 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 (with stream 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 = IntStream.range(0, keys.length).boxed()
    .collect(Collectors.toMap(i -> keys[i], i -> values[i]));

回答by Bhesh Gurung

IMHO, it's highly unlikely that you will find a utility like that.

恕我直言,您不太可能找到这样的实用程序。

But, even if you find one chances are really low that it will provide any performance gain. Because, I think you won't able to do it without iterate through all the elements in both the arrays.

但是,即使您发现它提供任何性能提升的机会非常低。因为,我认为如果不遍历两个数组中的所有元素,您将无法做到这一点。

One thing I can suggest is (only if your arrays have a huge number of elements) that you can specify the capacity of the map while instantiating it to reduce overhead of resizing while you put entries into it.

我可以建议的一件事是(仅当您的数组具有大量元素时)您可以在实例化映射时指定映射的容量,以减少在将条目放入其中时调整大小的开销。

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

回答by Lucky

Convert two String arrays to Map in Java

Java中将两个String数组转换为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]);
    }
 }

Check this LINKfor more solutions in different programming languages

检查此链接以获取更多不同编程语言的解决方案

Note: The keys should be unique..

Note: 键应该是唯一的..