简体   繁体   English

如果 Set 包含具有某些字符串值的对象,如何检查 Java?

[英]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.containsO(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...我知道这是一个老问题,但是......

Short answer: NO, it's not possible...简短回答:不,这是不可能的......

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 APIFunctional 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)。

Example with Java 8's stream().filter() Java 8 的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ãoMichael 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.

相关问题 如何检查字符串是否包含Java中的某些字符? - How to check if string contains some character in Java? 如何检查Set是否包含一个成员变量等于某个值的对象 - How to check if a Set contains an object which has one member variable equal to some value 如何检查字符串列表是否包含某个值以外的任何内容? - How to check if string list contains anything other than some value? 如何检查一组对象是否包含 object,该 object 的特定字段在 Java 中有特定值? - How can I check if a Set of objects contains an object having a specific fields with a specific value in Java? 如何检查TreeMap <String, ArrayList<String> &gt;是否包含值? 在Java中 - How to check if TreeMap<String, ArrayList<String>> contains a value? in Java 使用 Java Regex,如何检查字符串是否包含集合中的任何单词? - Using Java Regex, how to check if a string contains any of the words in a set ? Java如何检查数组列表中的对象是否包含某个值 - Java how to check if an object in an arraylist contains a certain value 如何在Java中检查字符串变量是否包含负值 - How to check if a string variable contains negative value or not in java 对象集包含按值包含对象的对象(非引用)(java 7) - Set of object contains by object with value (not reference) (java 7) 检查Java是否包含对象 - Check if a contains an object in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM