# 通过TreeSet以降序对数组进行排序，从而找到数组的第三大元素

``````// { Driver Code Starts
import java.util.Scanner;
import java.util.*;
import java.io.*;

class ThirdLargestElement
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
long n =sc.nextLong();
Long arr[] = new Long[(int)n];
for(long i=0;i<n;i++)
arr[(int)i] = sc.nextLong();
GfG g = new GfG();
System.out.println(g.thirdLargest(arr));
t--;
}
}
}// } Driver Code Ends
class GfG
{
long thirdLargest(Long a[])
{
// Your code here
if(a.length<3)
return -1;
else{
TreeSet<Long> ts=new TreeSet<Long>(new myComparator());
for(long i:a)
ts.add(i);
ArrayList<Long> al=new ArrayList<Long>(ts);
return al.get(2);
}
}
}
class myComparator implements Comparator{
public int compare(Object obj1,Object obj2){
Long a=(Long) obj1;
Long b=(Long) obj2;
if(a<b)
return 1;
else if(a>b)
return -1;
else
return 0;
}
}
``````

The testcase it failed:

Link to the question where you can run the code

• 给不了告白 回复

You can directly add elements to `TreeSet` and get third largest number using stream,

``````while(t>0)
{
long n =sc.nextLong();
TreeSet<Long> ts=new TreeSet<>(Comparator.comparingLong(Long::longValue).reversed());
for(long i=0;i<n;i++)
ts.add(sc.nextLong());
long thirdLast = ts.stream()
.limit(3)
.skip(2)
.mapToLong(e->e)
.findAny().orElse(0l);

System.out.println(thirdLast);
t--;
}
``````
• 猪坚强 回复

试试这个

``````class GfG {
long thirdLargest(Long a[]) {
Arrays.sort(a);
List<Long> numbers = Arrays.asList(a);
Collections.reverse(numbers);
return numbers.size() >= 3 ? numbers.get(2) : -1;
}
}

``````
• 咱，乖乖 回复

The question states:

函数thirdLargest ...具有两个参数。第一个参数是数组a []，第二个参数是数组的大小（n）。

尽管问题指出数组是...

一系列不同的元素

测试案例表明我们正在处理整数数组。

Personally, I don't see the need for the second method parameter, because in java an array is an object and has a `length` member. So my implementation below only takes one parameter, namely an array of `int`. Maybe the people at geeksforgeeks.org simply converted a question that was originally for the C language to java, since, in C, it is difficult to determine the size of any array.

Each element in a `TreeSet` must be an object, so we need to convert the elements in the `int` array to `Integer` objects. Autoboxing will do this automatically, nonetheless my code below contains an explicit conversion. So in the method I create a `TreeSet`. Since class `Integer` implements interface Comparable, the default `TreeSet` constructor is sufficient. I add all the elements of the `int` array to the `TreeSet`, then obtain a descending iterator and then iterate to the third element returned by the iterator, which is the value that the method needs to return.

``````    int thirdLargest(int[] arr) {
int third = -1;
if (arr != null  &&  arr.length > 2) {
TreeSet<Integer> set = new TreeSet<Integer>();
for (int elem : arr) {
set.add(Integer.valueOf(elem));
}
Iterator<Integer> iter = set.descendingIterator();
if (iter.hasNext()) {
iter.next();
if (iter.hasNext()) {
iter.next();
if (iter.hasNext()) {
third = iter.next().intValue();
}
}
}
}
return third;
}
``````

Of-course, if you want to ignore the conditions imposed by the original question, you could get the third largest element using the stream API

``````IntStream.of(2, 4, 1, 3, 5)
.boxed()
.sorted(Collections.reverseOrder())
.collect(Collectors.toList()).get(2)
``````