Practical Pair Examples
Real-World Pair Use Cases
1. Coordinate System Representation
public class CoordinateMapper {
public Pair<Double, Double> calculatePosition(double x, double y) {
double newX = x * 2;
double newY = y * 2;
return new Pair<>(newX, newY);
}
}
2. Student Grade Management
public class GradeTracker {
private List<Pair<String, Double>> studentGrades = new ArrayList<>();
public void addStudentGrade(String studentName, double grade) {
studentGrades.add(new Pair<>(studentName, grade));
}
public double getAverageGrade() {
return studentGrades.stream()
.mapToDouble(Pair::getValue)
.average()
.orElse(0.0);
}
}
Pair Processing Workflow
graph TD
A[Input Data] --> B[Create Pairs]
B --> C[Process Pairs]
C --> D[Extract Results]
Method Return with Multiple Values
public class DataProcessor {
public Pair<String, Integer> processData(List<Integer> numbers) {
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
String status = sum > 100 ? "High" : "Low";
return new Pair<>(status, sum);
}
}
Pair Collection Strategies
Strategy |
Description |
Use Case |
Grouping |
Collect related data |
Category mapping |
Caching |
Store intermediate results |
Performance optimization |
Validation |
Pair-based data checks |
Input verification |
Error Handling with Pairs
public class SafePairProcessor {
public Optional<Pair<String, Integer>> safeProcess(String input) {
try {
int value = Integer.parseInt(input);
return Optional.of(new Pair<>("Success", value));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
}
public class PairCache {
private Map<String, Pair<Long, String>> cache = new HashMap<>();
public Pair<Long, String> computeIfAbsent(String key) {
return cache.computeIfAbsent(key, k ->
new Pair<>(System.currentTimeMillis(), "Processed: " + k)
);
}
}
LabEx Learning Tip
Explore these practical Pair examples in LabEx's coding environments to enhance your Java skills and understand real-world applications.