試圖比較兩個串列中的兩個屬性。我通常比較它迭代兩個串列并比較每個元素(我認為這不是最佳的)。喜歡:
list1.forEach(x -> {
list2.forEach(y -> {
if (x.getId().compareTo(y.getId()) == 0)
x.setMyAttribute(y.getNameAttribute());
});
});
有沒有更好的方法來比較兩個串列中的特定屬性?盡管如此,我還是不明白如何使用HashMap,但我想知道HashMap這種比較是否更好用以及如何使用它。
我想我HashMap只能用idand name(我需要的屬性)創建一個。
uj5u.com熱心網友回復:
list2你分享的基本上是一個蠻力解決方案,它檢查list1.
而且你的想法是正確的。為避免執行冗余迭代,您可以list2通過生成HashMap將特定元素與其id.
我假設 的自然順序與它的實作id是一致的equals/hashCode,即(x.compareTo(y)==0) == (x.equals(y))因為它是推薦的做法(如果您使用id標準 JDK 類,例如Long, String,UUID情況就是這樣)。
這就是它的實作方式:
List<Foo> list1 = // initializing list1
List<Foo> list2 = // initializing list1
Map<ID, Foo> list2FoosById = list2.stream()
.collect(Collectors.toMap(
Foo::getId,
Function.identity(),
(left, right) -> right // remove merge function if IDs are expected to be unique
));
for (Foo x : list1) {
Foo y = list2FoosById.get(x.getId()); // retrieving Foo from list2 with the corresponding ID
if (y != null) x.setMyAttribute(y.getNameAttribute()); // reassign the attribute if the Foo having identical ID exists
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/527348.html
標籤:爪哇列表弹簧靴哈希图相比
上一篇:串列內的Javax驗證
