我有一個地圖 Map1 和另一個地圖 Map2 ..
地圖<Key,ProductEntity> Map1;
Map<Key, ProductEntitySecond> Map2;
我想在 map1 中迭代并檢查 Map1 的特定鍵是否存在于 Map2 中。如果是則回傳值。
有人可以給我一個想法來解決這類問題。
uj5u.com熱心網友回復:
也許你可以做這樣的事情:
map1
.entrySet()
.stream()
.filter(e -> map2.containsKey(e.getKey()))
.findFirst()
.map(e -> e.getValue())
.orElse(null);
因此,如果密鑰存在,map2它將回傳值,map1否則,它將回傳null
uj5u.com熱心網友回復:
您可以使用Stream API。
public class Application {
public static void main(String[] args) {
var map1 = new HashMap<Square, String>();
map1.put(new Square(2), "two");
map1.put(new Square(3), "three");
map1.put(new Square(4), "four");
map1.put(new Square(5), "five");
var map2 = new HashMap<Square, String>();
map2.put(new Square(2), "two");
map2.put(new Square(3), "three");
var valuesAlsoInMap2 = map1.entrySet().stream()
.filter(it -> map2.containsKey(it.getKey()))
.map(Map.Entry::getValue)
.toList();
System.out.println(valuesAlsoInMap2);
}
}
預期結果:
[two, three]
這是使用一個簡單的 POJOSquare來向您展示它確實適用于非原始型別。要查看 HashMap 所依賴的方法,請查看此執行緒。
import java.util.Objects;
class Square extends shape{
private int side;
public Square(int side) {
this.side = side;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Square square = (Square) o;
return side == square.side;
}
@Override
public int hashCode() {
return Objects.hash(side);
}
@Override
public double Area() {
return side*side;
}
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
}
uj5u.com熱心網友回復:
retainAll()這是另一種在兩個地圖的鍵集上使用交集運算 ( ) 的方法。
Map<Key, ProductEntity> map1 = ...;
Map<Key, ProductEntitySecond> map2 = ...;
Map<Key, ProductionEntity> tmp = new HashMap<>(map1);
tmp.keySet().retainAll(map2.keySet());
Collection<ProductionEntity> shared = tmp.values();
這既簡單又干凈,但它不是最有效的解決方案,如果在這種情況下很重要的話。
uj5u.com熱心網友回復:
我會給你一個非常非常簡單的例子。
如果您選擇使用與此類似的解決方案,我強烈建議您閱讀有關如何覆寫 Equals 和 Hashcode 的資訊:https ://www.baeldung.com/java-equals-hashcode-contracts
import java.util.Map;
import java.util.HashMap;
public class HelloWorld{
public static void main(String []args) {
Entity entity1 = new Entity();
entity1.id = 1L;
Entity entity2 = new Entity();
entity2.id = 1L;
Map map1 = new HashMap<Entity, String>();
map1.put(entity1, "one");
Map map2 = new HashMap<Entity, String>();
map2.put(entity2, "two");
System.out.println(map1.get(entity1));
System.out.println(map2.get(entity1));
}
private static class Entity {
public Long id;
@Override
public boolean equals(Object o) {
return ((Entity) o).id.equals(this.id);
}
}
}
正如您所看到的,即使是兩個不同但具有相同 id 的參考現在也被認為是相等的。
uj5u.com熱心網友回復:
適用于任何 Java 版本 8
List<String> valuesFromMap2WhenKeysAreCommon =
map1.keySet().stream().filter(map1::containsKey).map(map2::get).collect(Collectors.toList());
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456009.html
上一篇:檢索python字典的最后一個值
下一篇:如何將相同的字典鍵合并為一個?
