使用 class 可比 java 树图获取 containsValue

Get containsValue using class comparable java treemap

我是新手。 问题 1- 在将 count=5 的“Sam”添加到 TreeMap 之前,如何获取计数 值为 1 的“sam”? 即目前“sam”的计数为 5。我希望计数为 6。

问题 2- 关于 people3.containsKey,我怎样才能得到“containsValue”或“count” 对于那个记录?

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));
}