简体   繁体   English

如何基于这些对象的属性从对象列表中提取值?

[英]How can I extract values from a list of objects based on a property of these objects?

I'd like to find objects in a list based on having a certain property. 我想基于具有特定属性的列表中找到对象。

For example, say I have a list of objects of this class: 例如,说我有一个此类的对象列表:

class Person {
    private String name;
    private String id;
}

I know that I can get all of the names of people in the list by using: 我知道我可以使用以下方法获取列表中所有人员的姓名:

Collection<String> names = CollectionUtils.collect(
    personList,
    TransformerUtils.invokerTransformer("getName"));  

but what I want to do is get a list of the Person objects whose name is, for example, "Nick" . 但是我要做的是获取名称为例如"Nick"Person对象的列表。 I don't have Java 8. 我没有Java 8。

I see you are using Apache Common Utils, then you can use: 我看到您正在使用Apache Common Utils,然后可以使用:

CollectionUtils.filter( personList, new Predicate<Person>() {
    @Override
    public boolean evaluate( Person p ) {
        return p.getName() != null && p.getName().equals( "Nick" );
    }
});

If you don't want to use Java 8 streams, simply loop through the list and check the elements manually: 如果您不想使用Java 8流,只需遍历列表并手动检查元素:

ArrayList<Person> filteredList = new ArrayList<Person>();

for(Person person : personList) {
    if(person.getName().equals("Nick")) filteredList.add(person);
}

Using Apache collection utils (which you are already using), you can use the filter method which creates a subset of your collection consisting of items which match a given filter, combined with a Predicate that matches "Nick" based on your Transformer and transformedPredicate : 使用Apache集合utils(您已经在使用),可以使用filter方法创建集合的子集,该子集由与给定过滤器匹配的项组成,并结合基于TransformertransformedPredicate匹配“ Nick”的Predicate

CollectionUtils.filter(names, PredicateUtils.transformedPredicate(
    TransformerUtils.invokerTransformer("getName"), PredicateUtils.equalPredicate("Nick")));

That said, you may want to reconsider using such a heavily functional approach before you migrate to Java 8. Not only will you have a lot of redundant Apache collections code after you migrate, the solutions prior to the introduction of closures and lambdas tend to be verbose and often less readable than the imperative alternatives. 就是说,您可能要在迁移到Java 8之前重新考虑使用这种功能强大的方法。不仅在迁移之后,您将拥有许多冗余的Apache集合代码,而且在引入闭包和lambda之前的解决方案往往是冗长且通常不如命令性选项容易读。

Note: this modifies the existing collection in-place. 注意:这将就地修改现有集合。 If that is not the desired behavior, you'll need to create a copy before calling the filter method. 如果这不是所需的行为,则需要在调用filter方法之前创建一个副本。

You could try using a HashMap. 您可以尝试使用HashMap。

HashMap<String, Integer> points = new HashMap<String, Integer>();
    points.put("Amy", 154);
    points.put("Dave", 42);
    points.put("Rob", 733);
    System.out.println(points.get("Dave")); 

This would only be an example, but you could check and instead of having the String, Integer, you could try Integer, String and have an if statement . 这仅是一个示例,但是您可以检查而不是使用String,Integer,而可以尝试使用Integer,String并具有if statement Just an idea though. 虽然只是一个想法。

I am considering that you might have a collection of different objects that have this property name. 我正在考虑您可能具有此属性名称的不同对象的集合。 For that I would recommend you to do parent for those components and perform the search on it with generics: 为此,我建议您为这些组件做父级,并使用泛型对其进行搜索:

For example: 例如:

Parent class Name.java 父类Name.java

public class Name {

    private String name;

    public Name(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Class Pet.java 类Pet.java

public class Pet extends Name{

    public Pet(String name) {
        super(name);
    }

}

And class Person.java 和类Person.java

public class Person extends Name{

    public Person(String name) {
        super(name);
    }

}

Job class that doesn't have the property: 没有该属性的作业类别:

public class Job {

    private String description;

    public Job(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

Having that, you can check the instance of it and compare what you want: 有了它,您可以检查它的实例并比较所需的内容:

public static void main(String ... args) {
    List<Object> objectList = new ArrayList();
    objectList.add(new Person("Nick"));
    objectList.add(new Person("Nik"));
    objectList.add(new Person("Nikc"));
    objectList.add(new Person("Ncik"));
    objectList.add(new Pet("Nick"));
    objectList.add(new Pet("Nik"));
    objectList.add(new Pet("Nikc"));
    objectList.add(new Pet("Ncik"));
    objectList.add(new Job("Nick"));
    objectList.add(new Job("Nik"));
    objectList.add(new Job("Nikc"));
    objectList.add(new Job("Ncik"));

    for (Object o : extractObjectsMatching("Nick", objectList)){
        System.out.println(((Name) o).getName());
    }
}

public static List<Object> extractObjectsMatching(String name, List<Object> objectList){
    List<Object> matches = new ArrayList<>();
    for (Object e : objectList){
        if (e instanceof Name && ((Name) e).getName().contains(name)){
            matches.add(e);
        }
    }

    return matches;
}

If the Object class is not an instance of Name, means that will not have the property that you are looking for, just ignore, otherwise, compare with the information that you want and store to retrieve. 如果Object类不是Name的实例,则意味着将不具有您要查找的属性,请忽略,否则,将其与所需的信息进行比较并存储以检索。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从对象列表中提取K个“最小”元素? - How do I extract the K “smallest” elements from a list of objects? 如何使用SpEL提取列表中对象的单个属性列表? - How to extract list of single property of objects in list using SpEL? 如何有效地将 object AD 列表转换为 object BVo 列表? 两个对象具有相同的属性值 - How can I efficiently convert a list of object ADto to a list of object BVo? Both objects have the same property values 如何根据用户从下拉菜单中选择的参数对 Java 对象列表进行排序? - How can I sort a list of Java objects based on parameters that a user selects from a drop down menu? 如何从另一个类的属性文件中获取对象? - How can I get objects from property file in another classes? 如何根据两个对象参数对对象的链接列表进行排序? - How can I sort a linked list of objects based on two of the objects parameters? 如何从 ArrayList 获取具有相同对象属性的对象列表 - How to get a list of objects with same objects property from an ArrayList by 如何根据 java 中的属性值将对象列表转换为字符串列表? - How transform a list of objects to a list of strings based on the value of a property in java? 如何从类对象列表中提取值,删除重复项并按字母顺序排序? - How to extract values from a list of class objects, remove the duplicates and sort alphabetically? 我如何将属性值从一个对象传输到另一个对象 - How I can transfer atrributes values from a Objects to another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM