Class OpsRecord{
private String id;
private long sequenceNumber;
//implemented hashcode and equals method considering both id and version.
//So two OpsRecord are equal only if two OpsRecord has same id and sequenceNumber.
}
Class OpsCompleteRecord{
// This class has 20 class variables including id and sequenceNumber.
}
我的现有Map
具有以下值。假设值来自随机数据源。
Map<OpsRecord, OpsCompleteRecord> sourceMap = new HashMap<>();
sourceMap.put(new OpsRecord("1","1"), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1","3"), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1","2"), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2","2"), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2","1"), new OpsCompleteRecord());
我想要一个目标地图,其中只应包含OpsCompleteRecord
为1且id
为3的sequenceNumber
,以及另一个id
= 2且{{1} } = 2。
[sequenceNumber
]
sequenceNumber
targetMap
id
我正在尝试使用以下逻辑和代码实现。在填充targetMap时需要你的帮助。 我想我搞砸了逻辑。
new OpsRecord("1","3"), new OpsCompleteRecord()
new OpsRecord("2","2"), new OpsCompleteRecord()
我正在使用Java7。
答案 0 :(得分:2)
在 Java7 中,您可以尝试使用guava Maps.filterKeys
,例如:
Map<OpsRecord, OpsCompleteRecord> sourceMap = new HashMap();
sourceMap.put(new OpsRecord("1", 1), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1", 3), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1", 2), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2", 2), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2", 1), new OpsCompleteRecord());
Map<OpsRecord, OpsCompleteRecord> targetMap = Maps.filterKeys(sourceMap, new Predicate<OpsRecord>() {
@Override
public boolean apply(OpsRecord input) {
return input.id.equals(Long.toString(input.sequenceNumber));
}
});
在 Java8 中,您可以将stream
与filter
一起使用,collector
可以轻松完成此操作:
sourceMap.put(new OpsRecord("1", 1), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1", 3), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("1", 2), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2", 2), new OpsCompleteRecord());
sourceMap.put(new OpsRecord("2", 1), new OpsCompleteRecord());
Map<OpsRecord, OpsCompleteRecord> targetmap =
sourceMap.entrySet().stream()
.filter(i -> i.getKey().id.equals(Long.toString(i.getKey().sequenceNumber)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
需要另外注意的是:sequenceNumber
是long
类型,所以它应该使用new OpsRecord("2", 1)
。
希望它有用。