[英]How to check in java if Set contains object with some string value?
I have Set of objects.我有一组对象。 Each object has String value.
每个对象都有字符串值。
I need to select all objects that have this
value equal to "direction".我需要选择
this
值等于“方向”的所有对象。
Is it possible without iterating over the set?是否有可能不迭代集合?
In general, no.一般来说,没有。 You need to iterate over the set and check each object to see if the property is equal to the value you are searching for.
您需要遍历集合并检查每个对象以查看该属性是否等于您要搜索的值。 This is an
O(n)
operation.这是一个
O(n)
操作。
There is one situation in which you could do it without iterating.在一种情况下,您无需迭代即可完成。 If your object's
equals
method is defined in terms of equality of that String
property, and if the hashCode
method is also implemented correctly, then you can use the hashSet.contains
to find an object with the correct value in O(1)
time without requiring iterating over the set.如果您的对象的
equals
方法是根据该String
属性的相等性定义的,并且如果hashCode
方法也正确实现,那么您可以使用hashSet.contains
在O(1)
时间内找到具有正确值的对象,而无需迭代集合。
As I mentioned, this is a very specific use case and not a general solution.正如我所提到的,这是一个非常具体的用例,而不是一个通用的解决方案。 It might be useful if the string was some sort of unique identifier, but it won't work for your specific use case.
如果字符串是某种唯一标识符,它可能很有用,但它不适用于您的特定用例。
You might also want to consider other collections that would be better suited to your use case.您可能还想考虑更适合您的用例的其他集合。 You could for example if you are using Guava then you could consider using a Multimap .
例如,如果您使用的是 Guava,那么您可以考虑使用Multimap 。
Related有关的
Yes this is possible by overwriting the equals()
method .是的,这可以通过覆盖
equals()
方法来实现。
@Override
public boolean equals (Object object) {
}
You just want to check everything works in the equals method.您只想检查 equals 方法中的所有内容。
Code:代码:
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));
}
Output:输出:
Check checkUserOne is in list or not Is checkUserOne Present = ? true Check checkUserTwo is in list or not Is checkUserTwo Present = ? false
I know this is an old question, but...我知道这是一个老问题,但是......
Using equals()
or contains()
as recommended by other fellows should be restricted to situations where the attributes you are using for filtering are actually a part of the objects Identity.使用其他人推荐的
equals()
或contains()
应该仅限于您用于过滤的属性实际上是对象身份的一部分的情况。 I don't see any way but a O(n) algorithm.除了 O(n) 算法,我看不到任何方法。
If you are considering native functions, Java 8 brought the Stream API and concepts of Functional Programming , allowing easier and cleaner loop calls.如果您正在考虑原生函数,Java 8 带来了Stream API和Functional Programming 的概念,允许更简单、更清晰的循环调用。 Nonetheless it is worth noting that for your situation all objects in your collection will have to be checked, so complexity will remain O(n).
尽管如此,值得注意的是,对于您的情况,必须检查集合中的所有对象,因此复杂性将保持为 O(n)。
stream().filter()
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 集合的最佳方法是什么?
You still could use contains()
method as well.您仍然可以使用
contains()
方法。
You just need to map through your initial Set and transform it to the Set of string with only field values you want to check if they are existed in the Set of your object.您只需要映射您的初始 Set 并将其转换为 Set of string,其中只有您想要检查的字段值是否存在于您的对象的 Set 中。
See the next example based on previous answers from Felipe Leão and Michael Laffargue .请参阅基于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
} }
In my user class I have initialized roles variable like this private Set<\\Role> roles;在我的用户类中,我已经初始化了角色变量,比如这个private Set<\\Role> roles; .
. This has a getter method.
这有一个 getter 方法。 In the Role class I have String role variable where it is used to store the value of role.
在 Role 类中,我有 String 角色变量,用于存储角色的值。 In order to get the value of role.
为了获得角色的价值。 I can use below code.
我可以使用下面的代码。
for (Role role : user.getRoles()) {
rolevalue = role.getRole();
}
I solved this by using the Stream API :我通过使用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.