Ahsan Mahboob Shah
Ahsan Mahboob Shah

Reputation: 4029

How to get array of an specific attribute values from a list of custom object

I have a List<MyClass> and there is an attribute named attribute1 in MyClass.

Now the question is, how i can get the attribute1 values from List<MyClass> as an array without looping through the list in traditional way?

Upvotes: 1

Views: 3786

Answers (4)

Canberk
Canberk

Reputation: 435

You can create your own class which implements LIST interface. YOu should basically do the implementation which is exactly the same as one of the other implementation of list except;

1)you in your add method, every time you add a new element, append it in a string array which is a variable of your class.

2)and add an extra method, lets say giveMyAttribute1List and return the variable list I mentioned earlier.

you you basically have your answer.

List<MyClass> a = new myListIMpl<MyClass>();
a.giveMyAttribute1List();

Upvotes: 1

yamilmedina
yamilmedina

Reputation: 3395

You can use Guava's FluentIterable to collect your elements, here's an example assuming attribute1 is an Integer

    //populated
    List<MyClass> yourList;

    List<Integer> listbyAttribute = FluentIterable.from(yourList)
            .transform(new Function<MyClass, Integer>() {
        public Integer apply(MyClass f) {
            return f.getAttribute1();
        }
    }).toList();

More fun with this Guava class: here

Upvotes: 3

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279920

If you want to get the value of an attribute of each element in a List, you have to visit each element of that List. In other words, you have to iterate over each element. Whether you visit the elements in order with a loop or randomly in some ridiculous way, you're looping/iterating.

What you are asking for is not possible.

Upvotes: 0

Manuel
Manuel

Reputation: 4228

If this is some kind of tricky question where you (yourself) are not allowed to use a for-each, an iterator nor an old fashioned for-loop (like being asked in a job interview), I would suggest using the following:

Collections.sort(myList, myComparator)

and create the comparator

public class MyClassComparator implements Comparator<MyClass> {
    @Override
    public int compare(final MyClass o1, final MyClass o2) {
      // implement
    }
}

and implement the compare method in such a way, that the attribute1 is either in front (or back, or somewhere you know). Then you can easily fetch the element from the list without manually looping through it. But this answer applies only if this is some kind of "job interview question", otherwise looping through the list is most likely the only option you have.

Upvotes: 0

Related Questions