java 将基元数组值收集到Map类型的集合中

ni65a41a  于 2022-11-20  发布在  Java
关注(0)|答案(1)|浏览(160)

如何将基元值intlongdouble的数组转换为Map类型的集合?

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class PrimitiveStreamCollection {
    private static final String[] words = {
        "zero", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine"
    };
    
    private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 };

    public static Map<Integer, String> collect(int[] values) {
        return // Collect the array of values into a Map<Integer, String>
    }
    
    public static void main(String[] args) {
        Map<Integer, String> map = collect(numbers);
        System.out.println(map);
        // {0=zero, 3=three, 5=five, 6=six, 7=seven, 8=eight, 9=nine}
    }
}
edqdpe6u

edqdpe6u1#

以便将基元值数组转换为集合;这些值需要被boxed转换为相应的对象类型,或者需要调用原语流的collect方法。
拳击
下面是8个基本类型及其相应的 Package 类:

在下面的代码中,int[]转换为IntStream,然后将其装箱到Stream<Integer>中,并使用Collectors.toMap收集器进行收集。

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class PrimitiveStreamCollection {
    private static final String[] words = {
        "zero", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine"
    };

    private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 };

    public static Map<Integer, String> collectBoxed(int[] values) {
        return Arrays.stream(values)
            .boxed()
            .collect(
                Collectors.toMap(
                    Function.identity(),
                    value -> words[value]));
    }

    public static void main(String[] args) {
        Map<Integer, String> boxedMap = collectBoxed(numbers);
        System.out.println(boxedMap);
    }
}

原始流

Arrays.stream方法已被覆写,只接受doubleintlong的数组。

  • double[]DoubleStream
  • int[]IntStream
  • long[]LongStream

在下面的代码中,collect方法是直接在原语流对象上调用的,它有三个参数:

  • supplier-在本例中为HashMap<Integer, String>
  • accumulator-如何将iteree应用于供应商
  • combiner-如何组合多个值
import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class PrimitiveStreamCollection {
    private static final String[] words = {
        "zero", "one", "two", "three", "four",
        "five", "six", "seven", "eight", "nine"
    };

    private static final int[] numbers = { 8, 6, 7, 5, 3, 0, 9 };

    public static Map<Integer, String> collectUnboxed(int[] values) {
        return Arrays.stream(values)
            .collect(
                HashMap::new,
                (acc, value) -> acc.put(value, words[value]),
                HashMap::putAll);
    }

    public static void main(String[] args) {
        Map<Integer, String> unboxedMap = collectUnboxed(numbers);
        System.out.println(unboxedMap);
    }
}

相关问题