Java int[] array to HashSet

前端 未结 7 2100
感情败类
感情败类 2020-12-29 20:54

I have an array of int:

int[] a = {1, 2, 3};

I need a typed set from it:

Set s;

If I do th

7条回答
  •  有刺的猬
    2020-12-29 21:40

    The question asks two separate questions: converting int[] to Integer[] and creating a HashSet from an int[]. Both are easy to do with Java 8 streams:

    int[] array = ...
    Integer[] boxedArray = IntStream.of(array).boxed().toArray(Integer[]::new);
    Set set = IntStream.of(array).boxed().collect(Collectors.toSet());
    //or if you need a HashSet specifically
    HashSet hashset = IntStream.of(array).boxed()
        .collect(Collectors.toCollection(HashSet::new));
    

提交回复
热议问题