Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform a list into a map - foreach or streams?

I want to transform a List<String> into a Map<String, Integer>. The lists' values should serve as keys, and the map value will be statically initialized.

I want to keep the order of the list, thus using a LinkedHashMap, and ignore duplicates.

Question: is there any advantage using the java8 stream API? Because, comparing the following, simply regarding the syntax I'd never go for the verbose stream api, but always sticking to the old foreach loop:

    //foreach
    Map<String, Integer> map = new LinkedHashMap<>();
    for (String k : abk) {
        if (k != null) map.put(k, STATIC_VAL);
    }

    //streams
    Map<String, Integer> map2 = abk.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toMap(
                        Function.identity(),
                        k -> STATIC_VAL,
                        (v1, v2) -> v1,
                        LinkedHashMap::new));

Would you stick to the old approach or go with new lambda expressions?

like image 624
membersound Avatar asked Jul 06 '17 09:07

membersound


1 Answers

For this simple case I would stick to the for loop. It is faster too by the way (besides being more readable), Streams do have a cost of the infrastructure that has to be used. This new API is just a tool and as every tool is has pros/cons.

Generally I tent to used stream api only when I have to - let's say that the List needs filtered or mapped to something else, etc - then the Stream usage would make sense. If there are multiple operations that have to be done, it would make code way more readable then doing the same thing with a loop; but that's not always the case - as in your example.

Parallelization (in case you really need it is another aspect). Simple for loops are not easily parallelized, but with streams this is a breeze.

like image 187
Eugene Avatar answered Oct 26 '22 11:10

Eugene