简体   繁体   中英

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:

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:

            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:

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

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)

But to fill map with your expected values using stream api you can use forEach method and IntStream::iterate from java9

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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