How to convert List to Map with indexes using stream - Java 8?

前端 未结 4 1474
南笙
南笙 2020-12-15 03:00

I\'ve created method whih numerating each character of alphabet. I\'m learning streams(functional programming) and try to use them as often as possible, but I don\'t know ho

相关标签:
4条回答
  • 2020-12-15 03:43

    It is better to use Function.identity() in place of i->i because as per answer for this question:

    As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class.

    IntStream.range(0, alphabet.size())
             .boxed()
             .collect(toMap(alphabet::get, Function.identity()));
    
    0 讨论(0)
  • 2020-12-15 03:43

    using AtomicInteger, this method is stateless

        AtomicInteger counter = new AtomicInteger();
        Map<Character, Integer> map = characters.stream()
                .collect(Collectors.toMap((c) -> c, (c) -> counter.incrementAndGet()));
        System.out.println(map);
    
    0 讨论(0)
  • 2020-12-15 03:54

    Using streams with AtomicInteger in Java 8:

    private Map<Character, Integer> numerateAlphabet(List<Character> alphabet) {
        AtomicInteger index = new AtomicInteger();
        return alphabet.stream().collect(
                Collectors.toMap(s -> s, s -> index.getAndIncrement(), (oldV, newV)->newV));
    }
    
    0 讨论(0)
  • 2020-12-15 04:00

    Avoid stateful index counters like the AtomicInteger-based solutions presented in other answers. They will fail if the stream were parallel. Instead, stream over indexes:

    IntStream.range(0, alphabet.size())
             .boxed()
             .collect(toMap(alphabet::get, i -> i));
    

    Above assumes that the incoming list is not supposed to have duplicate characters since it's an alphabet. If you have possibility of duplicate elements then multiple elements will map to same key and then you need to specify merge function. For example you can use (a,b) -> b or (a,b) ->a as the third parameter to toMap method.

    0 讨论(0)
提交回复
热议问题