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

故事扮演 提交于 2020-01-02 02:11:27

问题


As for example, there are two lists:

List<Double> list1 = Arrays.asList(1.0, 2.0);
List<String> list2 = Arrays.asList("one_point_zero", "two_point_zero");

Using Stream, I want to create a map composed of these lists, where list1 is for keys and list2 is for values. To do it, I need to create an auxiliary list:

List<Integer> list0 = Arrays.asList(0, 1);

Here is the map:

Map<Double, String> map2 = list0.stream()
                .collect(Collectors.toMap(list1::get, list2::get));

list0 is used in order list1::get and list2::get to work. Is there a simpler way without creation of list0? I tried the following code, but it didn't work:

Map<Double, String> map2 = IntStream
                .iterate(0, e -> e + 1)
                .limit(list1.size())
                .collect(Collectors.toMap(list1::get, list2::get));

回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/39962796/creating-map-composed-of-2-lists-using-stream-collect-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!