简体   繁体   English

如何将字符串列表转换为LinkedHashMap?

[英]How to convert a list of Strings to a LinkedHashMap?

I have a list: 我有一个清单:

private List <String> list;

I want to convert it to a LinkedHashMap (to preserve order), such that the first two values in the map are a LinkedHashMap entry and so on until the list is a LinkedHashMap: 我想将其转换为LinkedHashMap(以保留顺序),以便地图中的前两个值是LinkedHashMap条目,依此类推,直到列表为LinkedHashMap:

private LinkedHashMap<String, String> linked;

This is what I have come up with. 这就是我想出的。 Admittedly I am new to the Collectors implementations so bear with me: 诚然,我是Collectors实现的新手,请耐心等待:

            linked = list.stream()
                .collect(Collectors.toMap(
                        Function.identity(),
                        String::valueOf, //Used to be String::length
                        LinkedHashMap::new));

this is giving me an error on the LinkedHashMap constructor line: 这在LinkedHashMap构造函数行上给了我一个错误:

Cannot resolve constructor of LinkedHashMap

This is an example of what the list may look like: 这是列表可能的示例:

zero
test0
one
test1
two
test2

and what I want the Map to look like: 以及地图的外观:

zero:test0
one:test1
two:test2

Thanks 谢谢

Why you complicate your code, a simple loop in your case solve the problem : 为什么使您的代码复杂化,一个简单的循环解决了这个问题:

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

Quick, Ideone demo 快速,Ideone演示

Outputs 产出

zero:test0
one:test1
two:test2

You missed merge function : 您错过了合并功能

a merge function, used to resolve collisions between values associated with the same key, as supplied to Map.merge(Object, Object, BiFunction) 合并函数,用于解决与相同键关联的值之间的冲突,如提供给Map.merge(Object,Object,BiFunction)

But to fill map with your expected values using stream api you can use forEach method and IntStream::iterate from java9 但是要使用流api用期望值填充地图,可以使用forEach方法和IntStream::iterate

LinkedHashMap<String, String> linked = new LinkedHashMap<>();

IntStream.iterate(0, n -> n < list.size(), n -> n + 2)
        .forEach(i -> linked.put(list.get(i), list.get(i + 1)));

This my attempt with java 8. 这是我对Java 8的尝试。

   IntStream.range(0, list.size())
            .mapToObj(index -> {
                    if (index % 2 == 0) {
                        return new AbstractMap.SimpleImmutableEntry<>(list.get(index), list.get(index + 1));
                    }
                    return null;
                }
            )
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(AbstractMap.SimpleImmutableEntry::getKey, AbstractMap.SimpleImmutableEntry::getValue));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM