How can I convert a Java HashSet to a primitive int array?

后端 未结 8 1897
既然无缘
既然无缘 2020-12-01 09:03

I\'ve got a HashSet with a bunch of Integers in it. I want to turn it into an array, but calling

hashset.toArray();
         


        
相关标签:
8条回答
  • 2020-12-01 09:59

    Try this. Using java 8.

        Set<Integer> set = new HashSet<>();
        set.add(43);
        set.add(423);
        set.add(11);
        set.add(44);
        set.add(56);
        set.add(422);
        set.add(34);
        int[] arr = set.stream().mapToInt(Integer::intValue).toArray();
    
    0 讨论(0)
  • 2020-12-01 10:02
    public int[] toInt(Set<Integer> set) {
      int[] a = new int[set.size()];
      int i = 0;
      for (Integer val : set) a[i++] = val;
      return a;
    }
    

    Now that I wrote the code for you it's not that manual anymore, is it? ;)

    0 讨论(0)
提交回复
热议问题