Search code examples
javalambdajava-streamlinkedhashmapcollectors

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


Solution

  • 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