Java转换列表<string>到Map <string,string =“”>

时间:2018-03-28 10:19:22

标签: java list collections hashmap java-stream

有没有一种很好的方法将字符串列表(使用Collectos API?)转换/转换为HashMap?

StringList和Map:

List<String> entries = new ArrayList<>();
HashMap<String, String> map = new HashMap<>();

...

My StringList包含如下字符串:

    entries.add("id1");
    entries.add("name1, district");
    entries.add("id2");
    entries.add("name2, city");
    entries.add("id3");
    entries.add("name3");

输出应为:

{id1=name1, district, id2=name2, city, id3=name3}

谢谢!

2 个答案:

答案 0 :(得分:9)

您不需要外部库,这很简单:

for (int i = 0; i < entries.size(); i += 2) {
  map.put(entries.get(i), entries.get(i+1));
}

或者,使用非随机访问列表的更有效方法是:

for (Iterator<String> it = entries.iterator(); it.hasNext();) {
  map.put(it.next(), it.next());
}

或者,使用流:

IntStream.range(0, entries.size() / 2)
    .mapToObj(i -> new SimpleEntry<>(entries.get(2*i), entries.get(2*i+1))
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

答案 1 :(得分:0)

Andy的答案肯定有效,而且这是一个很好的三线,但是this answer可能会解释如何使用Stream API来实现它。