Java – handle the properties of objects in the list?

In view of the following codes:

public class MyObject { 

String myProperty;

public MyObject(String propertyValue) {
    myProperty=propertyValue; 
}
}

and

public class Main {

public static void main(String[] args) {

    ArrayList<MyObject> objects = new ArrayList<MyObject>();
    objects.add(new MyObject("first"));
    objects.add(new MyObject("second"));
    objects.add(new MyObject("third"));

    // Now do Task A and Task B
}
}

Now I am looking for the best way to do the following:

Task a: find all objects with myproperty equal to "seconds" Is there anything similar

ArrayList<MyObject> filteredObjects = objects.findPropertyValue(myProperty,"second") ?

Task B: extract different myproperty values from the list, which means I want to get an array containing ("first", "second", "third"). Is there anything similar

ArrayList propertyValues = objects.getPropertyValues(myProperty) ?

I know that tasks a and B can be solved by looping through the ArrayList, but I wonder if there is a better way / content already built into eclipse? Thank you for your tips: -)

Please note that I don't want to use external libraries (I'm currently developing on Android and want to keep my application small)

Solution

If you need the first (task a), it may indicate that ArrayList is not the best data structure you should use This type of access should consider using map or Multimap (implemented in Apache common collections)

But... If you really need this kind of thing Several libraries come in handy

The most popular one is guava The other is lambdaj, which looks more professional:

// Task A
filter(having(on(MyObject.class).getPropertyValue(),equalTo("second")),objects);

// Task B
convert(objects,new PropertyExtractor("propertyValue"));
// or even
extract(objects,on(MyObject.class).getPropertyValue());

(I don't have a chance to compile / run the code I entered, so please don't be too strict)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>