如何解决如何在 Java 中的 SortedSet 中查找项目
我在 Java 中有一个 Sorted Set,其中一个对象有 2 个字符串,Name 和 Age。名称是唯一的。
我有我的对象:
capabilities: {
'browserName': 'chrome','platform': 'ANY','version': 'ANY','chromeOptions': {
args: ['--incognito'],}
里面有 3 个人:“John / 35”、“James / 21”和“Maria / 21”
基于此,我想检查一下詹姆斯的年龄。
我该怎么做?我唯一的想法就是做一个 for,但我想它应该更容易一些。
解决方法
我看到了两种解决方案:
- 如果真的只有这两个属性,您可以简单地将其转换为映射,其中名称是键,年龄是值(
Map<String,Integer> ageMap
)。然后您可以使用ageMap.get("James");
快速获取年龄。
编辑:要转换,您可以这样做:
Map<String,Integer> ageMap = new HashMap<>();
for (Person p : people) {
ageMap.put(p.getName(),p.getAge());
}
int jamesAges = ageMap.get("James");
-
如果您继续使用 Set 和 Person 类,我建议您使用流:
可选的 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。