Jon Jon - 1 month ago 7
Android Question

Android: Convenience method to convert arraylist<object> to arraylist<element>?

Assuming we have an object that looks like this:

public class myObject {

private String firstElement;
private Integer secondElement;
...

}


I have an arraylist of this object and I want to create an arraylist of only secondElement. Is there a convenience method to get all the secondElements out of all of the myObjects, or will I have to loop manually through the arraylist in order to create it?

Answer

If you use Java 8, you can use stream API to do that in one line :

List<Integer> mySecondList = Arrays.asList(myFirstList.stream().mapToInt(
    elem -> elem.getSecondElement()
).toArray());
Comments