Last active
August 22, 2024 08:58
-
-
Save MdGolam-Kibria/74b9cbba35cbbe6ee74bda1ad0da77bc to your computer and use it in GitHub Desktop.
get second highest salary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) { | |
int[] salaries = {100, 200, 500, 50, 30}; | |
int secondHighestSalary = Arrays.stream(salaries) | |
.distinct() // Remove duplicates if any | |
.sorted()//30,50,100,200,500 | |
.skip(salaries.length - 2) // Skip all without last 2 item = [200,500] | |
.findFirst()//200 | |
.orElseThrow(null); // Throw an exception if no element is found | |
System.out.println("Second highest salary: " + secondHighestSalary);//expected: 200 | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment