Home > Enterprise >  Java convert Int Array to SortedSet
Java convert Int Array to SortedSet

Time:10-14

How do I convert an int array to a SortedSet?

The following is not working,

SortedSet lst= new TreeSet(Arrays.asList(RatedMessage));

CodePudding user response:

public static NavigableSet<Integer> convertToSet(int... arr) {
    return Arrays.stream(arr).boxed().collect(Collectors.toCollection(TreeSet::new));
}

CodePudding user response:

Maybe you have to use Integer array, not simple int. It works this way:

int[] num = {1, 2, 3, 4, 5, 6, 7};

// Convert int[] --> Integer[]
Integer[] boxedArray = Arrays.stream(num)
    .boxed()
    .toArray(Integer[]::new);

SortedSet<Integer> sortedSet = new TreeSet<Integer>(Arrays.asList(boxedArray));

System.out.println("The SortedSet elements are :");

for(Integer element : sortedSet) {
      System.out.println(element);
}
  • Related