Java将Int Array转换为SortedSet



如何将int数组转换为SortedSet?

以下不起作用,

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

错误:

不能在java.util.TreeMap.compare(TreeMap.java:1290(上强制转换为java.lang.Comparable

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

也许您必须使用Integer数组,而不是简单的int。它是这样工作的:

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);
}

最新更新