class MyObject{
private String key;
private int value;
private int num;
}
创建对象的列表:对象列表的
List<MyObject> a = new ArrayList<MyObject>();
内容:
"Einstein",12,1
"Princeton",12,4
"Einstein",16,3
"Princeton",16,7
"Einstein",19,6
"Princeton",22,6
"Quantum",12,3
"Quantum",16,6
输入:"Einstein","Princeton","Quantum"
检查如果一个密钥存在于所有的值域中,如果s加起来的数字字段。在这种情况下,爱因斯坦,普林斯顿,量子只存在于价值12.因此增加了NUM场会给8.因此,
预计输出列表:
12,8
基本上我试图让交集对象的值字段和对应的num字段的总和。如何实现这一目标?
编辑: 列表xy = Arrays.asList(terms); //条件是输入
Map<Integer, Integer> check = new HashMap<Integer, Integer>();
for (int i = 0; i < a.size(); i++) {
if (xy.contains(a.get(i).getKey())) {
Integer sum = check.get(a.get(i).getNum());
if (sum == null)
sum = 0;
sum += a.get(i).getNum();
check.put(a.get(i).getValue(), sum);
}
}
列出内容:
Key: british Value: 899816511 Occ: 8
Key: naren Value: 899816511 Occ: 1
Key: einstein Value: 899816511 Occ: 1
Key: british Value: 562115287 Occ: 1
Key: einstein Value: 2056958632 Occ: 1
Key: british Value: 2056958632 Occ: 1
Key: einstein Value: 1426519040 Occ: 1
Key: british Value: 1426519040 Occ: 5
输入:"british","naren","einstein"
输出:
{1426519040=5, 562115287=1, 2056958632=1, 899816511=1}
你是什么意思与 “交集” 吗? – Manu343726
“交集”对于你想要做的事来说并不合适。为什么输出中不是'19,6'和'22,6'?因为它必须有2个“价值”元素才能显示出来?如果有2个以上的话? – Dukeling
num字段未使用。只有价值领域,因此19,6和22,6不考虑。 – NEO