Faisal khan Faisal khan -4 years ago 110
Java Question

How to get one attribute from list of custom objects

Java - JxPath - Spring

I have

List<MyClass> myClassList
filled with
MyClass
objects. I am trying to find a cleanest and fastest way to get
Set<String> a
property out of
myClassList
.

class MyClass{

private String a;
private String b;


// setters getters

}


I am using jxpath for searching but I am not sure it can also do what I mentioned above.

JXPathContext ctx = JXPathContext.newContext(myClassList);
Iterate<String> aProps = ctx.iterate("? what to write");


Can you help?

Answer Source

instead of Jxpath there is way doing it in Guava library.

here is the implementation

    public static final Function<Obj, String> FOO = new Function<Obj, String>() {
            public String apply(Obj input) {
                return input.foo;
            }
        };

List<String> fooList = Lists.transoform(targetList, Object.FOO)
or 
List<String> fooList = Collections2.transoform(targetList, Object.FOO)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download