我想打印哈希图中不存在于整数列表中的键。
例如。
`Map<Integer, String> PassengerInfo = new HashMap<>();
PassengerInfo.put(1, "komal"); //standard
PassengerInfo.put(2, "tejas"); //standard
PassengerInfo.put(3, "chetan"); //gold
PassengerInfo.put(4, "isha"); //premium
PassengerInfo.put(5, "chinmay"); //premium
PassengerInfo.put(6, "ashwini"); //standard
PassengerInfo.put(7, "ishwari"); //gold
PassengerInfo.put(8, "sam"); //gold
PassengerInfo.put(9, "tanu"); //premium
PassengerInfo.put(10, "ayush"); //premium
PassengerInfo.put(11, "harshali"); //gold
PassengerInfo.put(12, "prasad"); //standard
`
`
List<Integer> num = new LinkedList<>();
num.add(12);
num.add(9);
num.add(5);
我试过了,
for (Map.Entry<Integer, String> e : PassengerInfo.entrySet()){
for (int i=0; i<num.size();i++){
if (!e.getKey().equals(num.get(i))){
System.out.print(num.get(i)+" ");
}
}
}
o/p -> 12 9 5 12 9 5 12 9 5 12 9 5 12 9 12 9 5 12 9 5 12 9 5 12 5 12 9 5 12 9 5 9 5
但是我想要, 输出 -> 1, 2, 3, 4, 6, 7, 8, 10, 11 o/p 应该只打印一次
您可以循环并构建一个 Java Set,如果该元素尚未位于 Set 中,则打印并推送。
Set<Integer> set = new HashSet<Integer>();
for (Map.Entry<Integer, String> e : PassengerInfo.entrySet()){
for (int i=0; i<num.size();i++){
if (!set.contains(num.get(i))){
System.out.print(num.get(i)+" ");
set.add(num.get(i));
}
}
}