3

How do I convert an int array to a SortedSet?

The following is not working,

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

Error:

cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1290)

mattsmith5
  • 540
  • 4
  • 29
  • 67
  • 2
    search for "primitive" in https://stackoverflow.com/questions/3064423/how-to-convert-an-array-to-a-set-in-java – TomStroemer Oct 14 '22 at 08:17
  • 3
    Does this answer your question? [How to convert an Array to a Set in Java](https://stackoverflow.com/questions/3064423/how-to-convert-an-array-to-a-set-in-java) – HariHaravelan Oct 14 '22 at 08:20

2 Answers2

7
public static NavigableSet<Integer> convertToSet(int... arr) {
    return Arrays.stream(arr).boxed().collect(Collectors.toCollection(TreeSet::new));
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
1

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);
}
Péter Baráth
  • 316
  • 2
  • 10