Map Entry Immutable Key Value Pair
Carry key-value pairs through pipelines with the immutable Map.entry factory, whose instances reject setValue and slot into collectors without a map.
Code
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PairPipeline {
public static void main(String[] args) {
// Map.entry(k, v) 造不可变键值对:无需先建 Map
Map.Entry<String, Integer> pair = Map.entry("orders", 42);
System.out.println(pair.getKey() + " = " + pair.getValue());
// setValue 被直接拒绝:实例自创建起不可变
try {
pair.setValue(99);
} catch (UnsupportedOperationException e) {
System.out.println("setValue rejected");
}
// 流水线里成对传递,再一次性收进 Map
Map<String, Integer> plan = Stream.of(
Map.entry("stage-a", 1),
Map.entry("stage-b", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(plan);
// 重复键在 toMap 处炸出 IllegalStateException,成对数据更早暴露冲突
List<Map.Entry<String, Integer>> pairs = List.of(
Map.entry("env", "prod".length()),
Map.entry("env", "dev".length()));
try {
pairs.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} catch (IllegalStateException e) {
System.out.println("duplicate key detected");
}
}
}Inside the snippet
Map Entry Immutable Key Value Pair is built around the class PairPipeline and the function main.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector. Each demo rejection sits in its own plain try/catch — UnsupportedOperationException for setValue and IllegalStateException for a duplicate toMap key.
Points of care
- No package manager involved — every call resolves to a built-in API.
Putting it to use
The main signature reads public static void main(String[] args)
The file announces its steps in the output: setValue rejected, duplicate key detected.
Core lines
pairs.stream().collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Interactive Tools for This Topic
FAQ
- What does Map Entry Immutable Key Value Pair print when run?
- No setup needed: run the file and look for labeled lines like `setValue rejected`, `duplicate key detected` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.