Practical Examples
1. Student Grade Management System
public class StudentGradeComparison {
public static void main(String[] args) {
Map<String, Integer> studentScores = new HashMap<>();
studentScores.put("Alice", 95);
studentScores.put("Bob", 87);
studentScores.put("Charlie", 92);
// Sort students by score in descending order
List<Map.Entry<String, Integer>> topStudents = studentScores.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toList());
topStudents.forEach(entry ->
System.out.println(entry.getKey() + ": " + entry.getValue()));
}
}
2. Filtering Entries with Complex Conditions
public class AdvancedEntryFiltering {
public static void main(String[] args) {
Map<String, Employee> employeeMap = new HashMap<>();
employeeMap.put("E001", new Employee("John", 45000, "IT"));
employeeMap.put("E002", new Employee("Jane", 55000, "HR"));
// Filter high-performing employees in IT department
List<Map.Entry<String, Employee>> topITEmployees = employeeMap.entrySet().stream()
.filter(entry -> entry.getValue().getDepartment().equals("IT"))
.filter(entry -> entry.getValue().getSalary() > 50000)
.collect(Collectors.toList());
}
}
class Employee {
private String name;
private double salary;
private String department;
// Constructor, getters
}
3. Merging Map Entries
public class MapEntryMerging {
public static void main(String[] args) {
Map<String, Integer> map1 = Map.of("A", 1, "B", 2);
Map<String, Integer> map2 = Map.of("B", 3, "C", 4);
Map<String, Integer> mergedMap = Stream.of(map1, map2)
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> v1 + v2
));
}
}
Comparison Strategies Workflow
flowchart TD
A[Map Entries] --> B{Comparison Criteria}
B --> |By Key| C[Alphabetical Sorting]
B --> |By Value| D[Numerical Ranking]
B --> |Custom Logic| E[Advanced Filtering]
C --> F[Sorted Result]
D --> F
E --> F
Practical Scenario Comparison
Scenario |
Comparison Method |
Use Case |
Student Ranking |
Value Comparison |
Academic Performance |
Employee Filtering |
Custom Condition |
HR Management |
Data Aggregation |
Merging Entries |
Data Processing |
Key Takeaways
- Leverage Java Stream API for entry comparisons
- Use built-in and custom comparators flexibly
- Consider performance and readability
At LabEx, we emphasize practical skills in Java map entry manipulation to solve real-world programming challenges.