3 回答
TA贡献1828条经验 获得超13个赞
有很多方法可以做到这一点,但最清晰的方法可能是迭代一张地图的键集:
var voorspellingen = new LinkedHashMap<String, Integer>(); //ex: <user name, predicted score difference> var uitslagen = new LinkedHashMap<String, Integer>(); //... add data to maps here //Let's get a list of the users that gave good predictions Predicate<String> correctPrediction = name -> (uitslagen.get(name) != null && uitslagen.get(name).equals(voorspellingen.get(name))); List<String> correctUsers = uitslagen.keySet().stream() .filter(correctPrediction) .collect(Collectors.toList());
请注意,此解决方案不一定是最快的。我不知道你为什么选择 LinkedHashMap,但如果你有数百万用户,将预测和结果分组在同一个对象中确实可能更好。
TA贡献1845条经验 获得超8个赞
我建议只使用一个 HashMap,并且对于值,使用一个包含两个结果的对象。
class Results
{
int res1;
int res2;
}
使用上面的类作为你的值类,所以你只需要遍历HashMap一次来比较对象中的两个结果是否相等。
TA贡献1875条经验 获得超5个赞
我会用对象形式的值放入一张地图而不是两张地图。但是这里的权衡是我们将失去进入的最终值的序列。
import java.util.LinkedHashMap;
public class CompareTwoBets {
public static void main(String[] args) {
LinkedHashMap<String, Bet> map = new LinkedHashMap<>();
// First the users add prediction
map.put("jack", new Bet(1));
map.put("Bronwen", new Bet(2));
map.put("Cyrus", new Bet(2));
map.put("Brent", new Bet(5));
// now the users key in the definitive value
Bet bet = map.get("jack");
bet.setDefinitive(5);
map.put("jack", bet);
bet = map.get("Bronwen");
bet.setDefinitive(5);
map.put("Bronwen", bet);
bet = map.get("Cyrus");
bet.setDefinitive(5);
map.put("Cyrus", bet);
bet = map.get("Brent");
bet.setDefinitive(5);
map.put("Brent", bet);
System.out.println(map);
// process to know who put the bet accurately
map.forEach((user, x) -> {
if(x.definitive == x.predicted) {
System.out.println("User " + user +" predicted accurately." );
}
else {
System.out.println("User " + user +" predicted wrongly." );
}
});
}
}
public class User{
String firstName;
String lastName;
public User(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
public class Bet {
int predicted;
int definitive;
public Bet(int predicted) {
this.predicted = predicted;
}
public void setDefinitive(int definitive) {
this.definitive = definitive;
}
}
添加回答
举报