简体   繁体   English

在 Java 中使用 stream().collect 创建由 2 个列表组成的 Map

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

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.使用Stream,我想创建一个由这些列表组成的映射,其中list1 用于键,list2 用于值。 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. list0 按 list1::get 和 list2::get 的顺序使用。 Is there a simpler way without creation of list0?有没有更简单的方法而不创建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));

Instead of using an auxiliary list to hold the indices, you can have them generated by an IntStream .您可以使用IntStream生成索引,而不是使用辅助列表来保存索引。

Map<Double, String> map = IntStream.range(0, list1.size())
            .boxed()
            .collect(Collectors.toMap(i -> list1.get(i), i -> list2.get(i)));

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:实际上,最好的方法是使用IntStream.range(startInclusive, endExclusive)以使用get(index)访问两个列表的每个元素,最后使用Math.min(a, b)来避免在列表不存在时获得IndexOutOfBoundsException大小完全相同,因此最终代码将是:

Map<Double, String> map2 = IntStream.range(0, Math.min(list1.size(), list2.size()))
    .boxed()
    .collect(Collectors.toMap(list1::get, list2::get));

This works for me but is O(n^2):这对我有用,但是是 O(n^2):

    Map<Double, String> collect =
            list1.stream()
                    .collect(
                            toMap(Double::doubleValue, 
                                    item -> list2.get(list1.indexOf(item))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM