Creating Map composed of 2 Lists using stream().collect in Java

后端 未结 3 1994
再見小時候
再見小時候 2021-01-11 11:58

As for example, there are two lists:

List list1 = Arrays.asList(1.0, 2.0);
List list2 = Arrays.asList(\"one_point_zero\", \"two_p         


        
相关标签:
3条回答
  • 2021-01-11 12:20

    This works for me but is O(n^2):

        Map<Double, String> collect =
                list1.stream()
                        .collect(
                                toMap(Double::doubleValue, 
                                        item -> list2.get(list1.indexOf(item))));
    
    0 讨论(0)
  • 2021-01-11 12:36

    Instead of using an auxiliary list to hold the indices, you can have them generated by an IntStream.

    Map<Double, String> map = IntStream.range(0, list1.size())
                .boxed()
                .collect(Collectors.toMap(i -> list1.get(i), i -> list2.get(i)));
    
    0 讨论(0)
  • 2021-01-11 12:42

    Indeed the best approach is to use IntStream.range(startInclusive, endExclusive) in order to access to each element of both lists with get(index) and finally use Math.min(a, b) to avoid getting IndexOutOfBoundsException if the lists are not of the exact same size, so the final code would be:

    Map<Double, String> map2 = IntStream.range(0, Math.min(list1.size(), list2.size()))
        .boxed()
        .collect(Collectors.toMap(list1::get, list2::get));
    
    0 讨论(0)
提交回复
热议问题