Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get attributes list from ArrayList of objects

Tags:

java

arraylist

Suppose I have an object that looks like:

public class Obj {
String foo;
String bar;
}

If I create an arraylist of type Obj and populate it, is there a way I can return a list of all the objects in the array's foo attribute from the ArrayList?

EDIT: I should have been more clear, I did not want to do this via iteration

like image 975
ninjasense Avatar asked Jan 26 '11 17:01

ninjasense


People also ask

How do I get a list of fields from a list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do you get element from ArrayList?

The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned. It is of data-type int. Return Type: The element at the specified index in the given list.

Can we get index from value in ArrayList in Java?

indexOf() in Java. The indexOf() method of ArrayList returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

What are attributes of objects?

Attributes. An object characteristic that is always present and occupies storage, even if the attribute does not have a value. In this respect, an attribute is similar to a field in a fixed-length data structure.


1 Answers

Try this:

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

Use apache commons collection api.

like image 164
Surodip Avatar answered Nov 07 '22 01:11

Surodip