我有HashMap<String,Double>hm1
和guava table Table<String, String, Double> employeeYearsOfService
fatima |0.97
AT&T |0.96
Google={Bill Smith=1.75, Stacy Lerner=11.5},
Microsoft={Bill Smith=13.2,Stacy Lerner=3.5},
AT&T={Bill Smith=2.0, Stacy Lerner=1.4},
fatima={Bill Smith=1.0, Stacy Lerner=2.0}
fatima={Bill Smith=1.0, Stacy Lerner=2.0}
AT&T={Bill Smith=2.0, Stacy Lerner=1.4}
我希望通过创建新表Table<String, String, Double> results = HashBasedTable.create()
包含一行employeeYearsOfService
来获得此结果
谁与HashMap hm1
具有相同的密钥(这是我的问题)
表番石榴
Table<String, String, Double> employeeYearsOfService =
HashBasedTable.create();
employeeYearsOfService.put("AT&T", "Stacy Lerner", 1.4);
employeeYearsOfService.put("Microsoft", "Stacy Lerner", 3.5);
employeeYearsOfService.put("Microsoft", "Bill Smith", 13.2);
employeeYearsOfService.put("Google", "Stacy Lerner", 11.5);
employeeYearsOfService.put("AT&T", "Bill Smith", 2.0);
employeeYearsOfService.put("Google", "Bill Smith", 1.75);
employeeYearsOfService.put("fatima", "Bill Smith", 1.0);
employeeYearsOfService.put("fatima", "Stacy Lerner", 2.0);
hashmap hm1
HashMap<String, Double> hm = new HashMap<String, Double>();
HashMap<String, Double> hm1 = new HashMap<String, Double>();
System.out.println(employeeYearsOfService);
for (String key : employeeYearsOfService.rowKeySet()) {
for (Entry<String, Double> employee :
employeeYearsOfService.row(key).entrySet()) {
sum += employee.getValue() * operatCible.get(k);
sum2 += employee.getValue() * employee.getValue();
vect1 += operatCible.get(k) * operatCible.get(k);
Result = (sum / (sqrt(sum2) * sqrt(vect1)));
k++;
}
hm.put(key, Result);
k = 0;
sum = 0.0;
sum2 = 0.0;
vect1 = 0.0;
Result = 0.0;
}
System.out.println(hm);
Set<Entry<String, Double>> set = hm.entrySet();
List<Entry<String, Double>> list = new ArrayList<Entry<String, Double>>
(set);
Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
public int compare(Map.Entry<String, Double> o1,
Map.Entry<String, Double> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
System.out.println(list);
System.out.println("le K nn");
for (Entry<String, Double> entry : list.subList(0, 2)) {
hm1.put(entry.getKey(), entry.getValue());
}
新表循环
Table<String, String, Double> results = HashBasedTable.create();
System.out.println(hm1);
for (Entry<String, Double> entry : list) {
if(entry.getKey().equals(employeeYearsOfService.rowKeySet())){
results.put(employeeYearsOfService.row(entry.getKey())));
// how i do it
}
}
非常感谢
答案 0 :(得分:1)
一种方法是从表中删除您不想要的元素:
employeeYearsOfService.rowKeySet()
.removeIf(key -> !hm1.containsKey(key));
我在这里使用Table.rowKeySet
method从表中获取行键集。这个集合有界到原始表,这意味着当从该集合中删除一个元素时,将从表中删除整行(具有相同的键)。这就是我对Collection.removeIf
method所做的事情,如果true
地图中没有该密钥,则其谓词会返回hm1
。