Java int[] array to HashSet

前端 未结 7 2142
感情败类
感情败类 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:21

    Another option would be to use a primitive set from Eclipse Collections. You can easily convert an int[] to a MutableIntSet to a Set or Integer[] as shown below, or you can use the MutableIntSet as is which will be much more memory efficient and performant.

    int[] a = {1, 2, 3};
    MutableIntSet intSet = IntSets.mutable.with(a);
    Set integerSet = intSet.collect(i -> i);  // auto-boxing
    Integer[] integerArray = integerSet.toArray(new Integer[]{});
    

    If you want to go directly from the int array to the Integer array and preserve order, then this will work.

    Integer[] integers = 
            IntLists.mutable.with(a).collect(i -> i).toArray(new Integer[]{});
    

    Note: I am a committer for Eclipse Collections

提交回复
热议问题