使用类可比较的java树映射获取containsValue



我是个新手。问题1-在添加";Sam"如果count=5到TreeMap,我如何获得计数的";sam";值为1?即当前";sam";将计数为5。我希望计数为6。

问题2-关于people3.containsKey,我如何才能得到"containsValue;或";计数";为了那张唱片?

TIA-

package app;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
class Person implements Comparable<Person> {
private String name;
public Person(String name) {
this.name = name;
}
public String toString() {
return name;
}
//  below sorts in alphabetic
@Override
public int compareTo(Person other) {
return this.name.compareToIgnoreCase(other.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
return Objects.equals(name, other.name);
}
}
public class App {
public static void main(String[] args) {
TreeMap<Person, Integer> people3 = new TreeMap<>();
int count = 1;
people3.put(new Person("sam"), count);
people3.put(new Person("Tom"), count);
people3.put(new Person("Bob"), count);
count = 5;
people3.put(new Person("Sam"), count);
Set<Map.Entry<Person, Integer>> entrySet = people3.entrySet();
int loop = 0;
String strFind = "Tom";
if (people3.containsKey(new Person(strFind))) {
System.out.println("_How do I get the count for " + strFind + " ?");
}
for (Entry<Person, Integer> currentEntry : entrySet) {
var uniqword = currentEntry.getKey();
var sumcount = currentEntry.getValue();
loop++;
System.out.println("(" + loop + " ) " + uniqword + ": " + sumcount);
}
}
}

对于第一个问题,请使用merge而不是put

TreeMap<Person, Integer> people3 = new TreeMap<>();
int count = 1;
people3.put(new Person("Sam"), count);
people3.put(new Person("Tom"), count);
people3.put(new Person("Bob"), count);
count = 5;
people3.merge(new Person("Sam"), count, (oldVal, newVal) -> oldVal + newVal);
// or shorter
people3.merge(new Person("Sam"), count, Integer::sum);

对于第二个问题,只需使用get

Person personToFind = new Person("Tom");
if (people3.containsKey(personToFind)) {
System.out.println("The count for " + personToFind + people3.get(personToFind));
}

相关内容

  • 没有找到相关文章

最新更新