Skip to content

Instantly share code, notes, and snippets.

@MdGolam-Kibria
Last active August 22, 2024 08:58
Show Gist options
  • Save MdGolam-Kibria/74b9cbba35cbbe6ee74bda1ad0da77bc to your computer and use it in GitHub Desktop.
Save MdGolam-Kibria/74b9cbba35cbbe6ee74bda1ad0da77bc to your computer and use it in GitHub Desktop.
get second highest salary
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