如何在 Java 中的 SortedSet 中查找项目

how to find an item in a SortedSet in Java

我在 Java 中有一个排序集,其中一个对象包含 2 个字符串,名称和年龄。名称是唯一的。

现在我有了名字,我想根据名字得到年龄。

我有我的对象:

SortedSet<Person> people;

里面有 3 个人:“John / 35”、“James / 21”和“Maria /21”

据此,我想查询一下詹姆斯的年龄

我该怎么做?我唯一的想法就是做一个for,但我想它应该更容易一些。

我看到了两个解决方案:

  1. 如果真的只有这两个属性,您可以简单地将其转换为映射,其中名称是键,年龄是值,(Map<String, Integer> ageMap)。然后你可以通过ageMap.get("James");.
  2. 快速获取年龄

编辑:要进行转换,您可以这样做:

Map<String, Integer> ageMap = new HashMap<>();
for (Person p : people) {
   ageMap.put(p.getName(), p.getAge());
}
int jamesAges = ageMap.get("James");
  1. 如果你继续使用 Set 和 Person class,我建议使用流:

    可选的 findFirst = set.stream().filter(e -> e.getName().equals("James")).findFirst();

    if (findFirst.isPresent()) {

     int age = findFirst.get().getAge();
    

    }

在内部,这可能仍会使用某种 for,但实际实现可能会更优化一些。

我不会为此使用集合,因为您无法轻松地从集合中检索值。我会带着地图去。您可以随意填充地图。

class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    @Override
    public String toString() {
        return "[" + name + ", " + age +"]";
    }
}

Map<String, Person> people = new HashMap<>(Map.of("john", new Person("John",35),
        "james", new Person("James", 21), "maria", new Person("Maria", 21)));


String name = "James";
Person person = people.get(name.toLowerCase());
System.out.println(person != null 
           ?  name + "'s age is "+ person.getAge()
           : name + " not found");

打印

James's age is 21