要创建排序集,首先创建一个集-
Set<Integer> s = new HashSet<Integer>();
将元素添加到上述集合中-
int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89}; Set<Integer> s = new HashSet<Integer>(); try { for(int i = 0; i < 5; i++) { s.add(a[i]); }
之后,使用TreeSet类进行排序-
TreeSet sorted = new TreeSet<Integer>(s);
使用last()
方法获取最后一个元素-
System.out.println("\nLast element of the sorted set = "+ (Integer)sorted.last());
以下是从Java中的排序集中获取最后一个元素的代码-
import java.util.*; public class Demo { public static void main(String args[]) { int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89}; Set<Integer> s = new HashSet<Integer>(); try { for(int i = 0; i < 5; i++) { s.add(a[i]); } System.out.println(s); TreeSet sorted = new TreeSet<Integer>(s); System.out.println("Sorted list = "); System.out.println(sorted); System.out.println("\nLast element of the sorted set = "+ (Integer)sorted.last()); } catch(Exception e) {} } }
输出结果
[66, 99, 4, 23, 77] Sorted list = [4, 23, 66, 77, 99] Last element of the sorted set = 99