java 将静态二维字符串数组转换为 HashMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1702565/
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-29 17:40:34  来源:igfitidea点击:

converting static 2D String array to HashMap

java

提问by Casey

What is the easiest way to convert a 2D array of Strings into a HashMap?

将二维字符串数组转换为 HashMap 的最简单方法是什么?

For example, take this:

例如,拿这个:

final String[][] sheetMap = { /* XSD Name,  XSL Sheet Name */
                              {"FileHeader", "FileHeader"}, 
                              {"AccountRecord", "AccountRecord"}, 
                              {"DriverCardRecord", "DriverCardRecord"}, 
                              {"AssetCardRecord", "AssetCardRecord"},
                              {"SiteCardRecord", "SiteCardRecord"}
                            };

This is most likely going to be loaded from a file and will be much bigger.

这很可能是从文件中加载的,并且会更大。

回答by Andrzej Doyle

final Map<String, String> map = new HashMap<String, String>(sheetMap.length);
for (String[] mapping : sheetMap)
{
    map.put(mapping[0], mapping[1]);
}

回答by tangens

If you just want to initialize your map in a convenient way, you can use double brace initialization:

如果您只想以方便的方式初始化您的地图,您可以使用双括号初始化

Map<String, String > sheetMap = new HashMap<String, String >() {{
   put( "FileHeader", "FileHeader" ); 
   put( "AccountRecord", "AccountRecord" ); 
   put( "DriverCardRecord", "DriverCardRecord" ); 
   put( "AssetCardRecord", "AssetCardRecord" );
   put( "SiteCardRecord", "SiteCardRecord" );
}};

回答by dwellman

As a slightly cleaner alternative to tradeJmark answer:

作为tradeJmark答案的更清洁的替代方案:

String[][] arr = // your two dimensional array
Map<String, String> arrMap = Arrays.stream(arr).collect(Collectors.toMap(e -> e[0], e -> e[1]));

// Sanity check!
for (Entry<String, String> e : arrMap.entrySet()) {
    System.out.println(e.getKey() + " : " + e.getValue());
}

回答by Simon Jenkins

More concise with streams would be:

更简洁的流将是:

 import static java.util.Arrays.stream;
 import static java.util.stream.Collectors.toMap;
 import java.util.Map;

     ...

 public static Map<String, String> asMap(String[][] data) {
     return stream(data).collect(toMap( m->m[0], m->m[1] ));
 }

     ...

回答by Kevin Bourrillion

Wait; if this is going to be loaded from a file, don'tgo through the intermediate array step! You would have had to load it all first before creating the array or you wouldn't know the size for the array. Just create a HashMap and add each entry as you read it.

等待; 如果这是从文件加载,不要通过中间数组步骤!在创建数组之前,您必须首先加载它,否则您将不知道数组的大小。只需创建一个 HashMap 并在阅读时添加每个条目。

回答by Tim M.

The existing answers work well, of course, but in the interest of continually updating this site with new info, here's a way to do it in Java 8:

现有的答案当然很好用,但为了不断用新信息更新这个站点,这里有一种在 Java 8 中实现的方法:

String[][] arr = {{"key", "val"}, {"key2", "val2"}};
HashMap<String, String> map = Arrays.stream(arr)
        .collect(HashMap<String, String>::new,
                (mp, ar) -> mp.put(ar[0], ar[1]),
                HashMap<String, String>::putAll);

Java 8 Streams are awesome, and I encourage you to look them up for more detailed info, but here are the basics for this particular operation:

Java 8Stream很棒,我鼓励您查找它们以获取更详细的信息,但以下是此特定操作的基础知识:

  • Arrays.streamwill get a Stream<String[]>to work with.
  • collecttakes your Streamand reduces it down to a single object that collects all of the members. It takes three functions. The first function, the supplier, generates a new instance of an object that collects the members, so in our case, just the standard method to create a HashMap. The second function, the accumulator, defines how to include a member of the Streaminto the target object, in your case we simply want to putthe key and value, defined as the first and second value from each array, into the map. The third function, the combiner, is one that can combine two of the target objects, in case, for whatever reason, the JVM decided to perform the accumulation step with multiple HashMaps (in this case, or whatever other target object in another case) and then needs to combine them into one, which is primarily for asynchronous execution, although that will not typically happen.
  • Arrays.stream将得到一个Stream<String[]>工作。
  • collect将您的Stream内容简化为一个收集所有成员的对象。它需要三个功能。第一个函数,供应商,生成一个对象的新实例来收集成员,所以在我们的例子中,只是创建一个HashMap. 第二个函数,累加器,定义了如何将 的成员包含Stream到目标对象中,在您的情况下,我们只想put将键和值(定义为每个数组的第一个和第二个值)放入映射中。第三个函数是组合器,它可以组合两个目标对象,以防万一,无论出于何种原因,JVM 决定对多个对象执行累加步骤HashMaps(在这种情况下,或在另一种情况下的任何其他目标对象),然后需要将它们组合成一个,这主要用于异步执行,尽管这通常不会发生。

回答by Ravinda lakshan

Java 8 way

Java 8 方式

  public static Map<String, String> convert2DArrayToMap(String[][] data){
    return Arrays.stream(data).collect(Collectors.toMap(m -> m[0], m -> m[1]));
  }

with loop

带循环

public static Map<String, String> convert2DArrayToMap(String[][] data)
  {
    Map<String, String> map = new HashMap<>();
    for (String[] m : data)
    {
      if (map.put(m[0], m[1]) != null)
      {
        throw new IllegalStateException("Duplicate key");
      }
    }
    return map;
  }