-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFindYoungest.java
More file actions
56 lines (47 loc) · 1.73 KB
/
Copy pathFindYoungest.java
File metadata and controls
56 lines (47 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package interviewQuestions;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class FindYoungest {
public static void main(String[] args) {
test1();
// test2();
}
static void test1() {
// Creating a HashMap to store student names and their ages
HashMap<String, Integer> students = new HashMap<>();
// Adding student data
students.put("Alice", 20);
students.put("Bob", 19);
students.put("Charlie", 22);
students.put("David", 18);
students.put("Emma", 21);
// Finding the youngest student
String youngestStudent = null;
int minAge = Integer.MAX_VALUE;
for (Map.Entry<String, Integer> entry : students.entrySet()) {
if (entry.getValue() < minAge) {
minAge = entry.getValue();
youngestStudent = entry.getKey();
}
}
// Printing the youngest student name
System.out.println("The youngest student is: " + youngestStudent + " (Age: " + minAge + ")");
}
static void test2() {
// Creating a HashMap to store student names and their ages
Map<String, Integer> students = new HashMap<>();
students.put("Alice", 20);
students.put("Bob", 19);
students.put("Charlie", 22);
students.put("David", 18);
students.put("Emma", 21);
// Finding the youngest student using Streams
students.entrySet()
.stream()
.min(Entry.comparingByValue())
.ifPresent(youngest ->
System.out.println("The youngest student is: "
+ youngest.getKey() + " (Age: " + youngest.getValue() + ")"));
}
}