迭代两个hashMap并比较键并比较形成键的元素以填充最终的hashMap

时间:2016-09-08 04:08:59

标签: java hashmap

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。

1 个答案:

答案 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 中,您可以将streamfilter一起使用,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));

需要另外注意的是:sequenceNumberlong类型,所以它应该使用new OpsRecord("2", 1)

希望它有用。