[英]How to check in java if Set contains object with some string value?
我有一組對象。 每個對象都有字符串值。
我需要選擇this
值等於“方向”的所有對象。
是否有可能不迭代集合?
一般來說,沒有。 您需要遍歷集合並檢查每個對象以查看該屬性是否等於您要搜索的值。 這是一個O(n)
操作。
在一種情況下,您無需迭代即可完成。 如果您的對象的equals
方法是根據該String
屬性的相等性定義的,並且如果hashCode
方法也正確實現,那么您可以使用hashSet.contains
在O(1)
時間內找到具有正確值的對象,而無需迭代集合。
正如我所提到的,這是一個非常具體的用例,而不是一個通用的解決方案。 如果字符串是某種唯一標識符,它可能很有用,但它不適用於您的特定用例。
您可能還想考慮更適合您的用例的其他集合。 例如,如果您使用的是 Guava,那么您可以考慮使用Multimap 。
有關的
是的,這可以通過覆蓋equals()
方法來實現。
@Override
public boolean equals (Object object) {
}
您只想檢查 equals 方法中的所有內容。
代碼:
package com.webapp.test;
import java.util.ArrayList;
import java.util.List;
public class EmployeeModel {
public EmployeeModel(String name, String designation, long age) {
this.name = name;
this.designation = designation;
this.age = age;
}
private String name;
private String designation;
private long age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public long getAge() {
return age;
}
public void setAge(long age) {
this.age = age;
}
@Override
public boolean equals (Object object) {
boolean result = false;
if (object == null || object.getClass() != getClass()) {
result = false;
} else {
EmployeeModel employee = (EmployeeModel) object;
if (this.name == employee.getName() && this.designation == employee.getDesignation() && this.age.equals(employee.getAge())) {
result = true;
}
}
return result;
}
}
public static void main(String args[]) {
EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);
List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
employeeList.add(first);
employeeList.add(second);
employeeList.add(third);
EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
System.out.println("Check checkUserOne is in list or not ");
System.out.println("Is checkUserOne Present = ? " + employeeList.contains(checkUserOne));
EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
System.out.println("Check checkUserTwo is in list or not");
System.out.println("Is checkUserTwo Present = ? " + employeeList.contains(checkUserTwo));
}
輸出:
Check checkUserOne is in list or not Is checkUserOne Present = ? true Check checkUserTwo is in list or not Is checkUserTwo Present = ? false
我知道這是一個老問題,但是......
使用其他人推薦的equals()
或contains()
應該僅限於您用於過濾的屬性實際上是對象身份的一部分的情況。 除了 O(n) 算法,我看不到任何方法。
如果您正在考慮原生函數,Java 8 帶來了Stream API和Functional Programming 的概念,允許更簡單、更清晰的循環調用。 盡管如此,值得注意的是,對於您的情況,必須檢查集合中的所有對象,因此復雜性將保持為 O(n)。
stream().filter()
示例public static void main(String[] args...){
Set<MyClass> mySet = new HashSet<>();
mySet.add(new MyClass("Obj 1", "Rio de Janeiro"));
mySet.add(new MyClass("Obj 2", "London"));
mySet.add(new MyClass("Obj 3", "New York"));
mySet.add(new MyClass("Obj 4", "Rio de Janeiro"));
Set<MyClass> filtered = mySet.stream()
.filter(mc -> mc.getCity().equals('Rio de Janeiro'))
.collect(Collectors.toSet());
filtered.forEach(mc -> System.out.println("Object: "+mc.getName()));
// Result:
// Object: Obj 1
// Object: Obj 4
}
您也可以像在這個問題中一樣使用Predicate
來過濾列表: 過濾 Java 集合的最佳方法是什么?
您仍然可以使用contains()
方法。
您只需要映射您的初始 Set 並將其轉換為 Set of string,其中只有您想要檢查的字段值是否存在於您的對象的 Set 中。
請參閱基於Felipe Leão和Michael Laffargue之前回答的下一個示例。
public static void main(String[] args...){
Set<MyClass> mySet = new HashSet<>();
mySet.add(new MyClass("Obj 1"));
mySet.add(new MyClass("Obj 2"));
mySet.add(new MyClass("Obj 3"));
Set<String> mapped = mySet.stream()
.map(MyClass::getField())
.collect(Collectors.toSet());
mapped.contains("Obj 1");
mapped.contains("Obj 2");
mapped.contains("Obj 4");
// Result:
// true
// true
// false
}
在我的用戶類中,我已經初始化了角色變量,比如這個private Set<\\Role> roles; . 這有一個 getter 方法。 在 Role 類中,我有 String 角色變量,用於存儲角色的值。 為了獲得角色的價值。 我可以使用下面的代碼。
for (Role role : user.getRoles()) {
rolevalue = role.getRole();
}
我通過使用Stream API解決了這個問題:
Student ousama = students.stream()
.filter(student -> "ousama".equals(student.getName()))
.findAny()
.orElse(null);
if(ousama != null) {
//Exist
} else {
//Doesn't exist
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.