1

I'm trying to write a program that print out the third largest number stored in an ArrayList. I tried sorting it then reversing the list to the and using get() method to get the index of third highest number. But it doesn't take into account how if there duplicates in the first 3 slots.

How do iterate through the arraylist to get the third highes value?

What I have done so far.

import java.util.*;

public class third {
    public static void main(String[] args) {
       

        ArrayList<Integer> numbers = new ArrayList<>(); //creating an array object
        Scanner scan = new Scanner(System.in); // scanner to read user input

        
        // print statement to get input
        System.out.print("Enter any amount of numbers: "); 
        int i = 0;
        while (scan.hasNextInt()) {// while there is an hasnext has an int                
            numbers.add(scan.nextInt()); //adding input(numbers) to an arraylist
            i++; //increment by 1                     
        } 
        scan.close(); // close the scanner if the user doesnt enter a number.
        
        System.out.println("you entered: " + numbers);
        System.out.println("The largest number you entered is: " + Collections.max(numbers));//print largest number
        System.out.println("The smallest number you entered is: " + Collections.min(numbers));//print smallest number

        Collections.sort(numbers); //sorting the numbers from lowest to highest
        System.out.println("Sorted: " + numbers); //print sorted numbers

        Collections.reverse(numbers); //reverse the order to use to get the third highest value
        System.out.println("Highest to lowest: " + numbers);
        System.out.println("Third highest number is:" + numbers.get(2));//get the third index of the sorted ArrayList       
        }
}
2
  • Use a Set instead of ArrayList? Commented Nov 20, 2020 at 10:06
  • looping 3 times would yield a simplest efficient approach than what you have written. Commented Nov 20, 2020 at 10:57

4 Answers 4

1

There is a need of a loop at the last to discard the duplicates and find exact third largest number. As i have done.

import java.util.*;

public class third {
public static void main(String[] args) {
   

    ArrayList<Integer> numbers = new ArrayList<>(); //creating an array object
    Scanner scan = new Scanner(System.in); // scanner to read user input

    
    // print statement to get input
    System.out.print("Enter any amount of numbers: "); 
    int i = 0;
    while (scan.hasNextInt()) {// while there is an hasnext has an int                
        numbers.add(scan.nextInt()); //adding input(numbers) to an arraylist
        i++; //increment by 1                     
    } 
    scan.close(); // close the scanner if the user doesnt enter a number.
    
    System.out.println("you entered: " + numbers);
    System.out.println("The largest number you entered is: " + Collections.max(numbers));//print largest number
    System.out.println("The smallest number you entered is: " + Collections.min(numbers));//print smallest number

    Collections.sort(numbers); //sorting the numbers from lowest to highest
    System.out.println("Sorted: " + numbers); //print sorted numbers

    Collections.reverse(numbers); //reverse the order to use to get the third 
    highest value
    System.out.println("Highest to lowest: " + numbers);
    int counter=0; // To find distinct number 
    for(int i=numbers.size()-1 ; i>=0 ; i--){ // Another loop to by pass 
    //duplicates
    if(numbers.get(i)!=numbers.get(i-1)){
    counter++;
    }
    if(counter==2){      // third highest
      System.out.println("Third highest number is:" + numbers.get(i));//get
    //third index of the sorted ArrayList 
    break;
    }
         
    }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

This worked perfectly, thanks. but i would like to know what this if loop is doing exactly. if(numbers.get(x)!=numbers.get(x-1)){ counter++;
It just checks that after sorting and reversing if there exists a duplicate. if there is no duplicate it will increment this counter. Once the value of this counter becomes 2 it means we have reached to third highest number.
1

Pass the arraylist values to the hashmap. Or else store the values in the hashmap. Hashmap contains No Duplicates. after that reverse the collection and do as u did.

Comments

1

In order to find the third largest element, simply create a SortedSet from your list of numbers. If the set contains at least three elements then the third last element is the one you want. In order to get the third last element, convert the SortedSet to an array. See below code. Note that SortedSet is an interface that is implemented by class TreeSet.

SortedSet<Integer> ss = new TreeSet<>(numbers);
if (ss.size() > 2) {
    System.out.println("Third highest number is:" + ss.toArray(new Integer[0])[ss.size() - 3]);//get the third index of the sorted ArrayList
}

Comments

1

You use SortedSet to sorting and deleted duplicates, so instead of Collections.sort(numbers); you can use (draft, not checking):

 SortedSet<Integer> numbersSet = new TreeSet<>(numbers );
 numbers = new ArrayList<>(numbersSet);
 Collections.reverse(numbers);        

 Collections.reverse(numbers); //reverse the order to use to get the third highest value
 System.out.println("Highest to lowest: " + numbers);
 System.out.println("Third highest number is:" + numbers.length() > 2? numbers.get(2): "not found");//get the third index of the sorted ArrayList       

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.