Java8 Transform list of object to list of one attribute of object
This should do the trick:
objects.stream().map(MyObj::getId).collect(Collectors.toList());
that said, the method reference ::
operator allows you to reference any method in your classpath and use it as a lambda for the operation that you need.
As mentioned in the comments, a stream preserves order.
Nik
I am a grad student studying Computer Science. My interests are in data-driven applications, web technologies and machine learning. I love coding and am a big fan of Python even though I started using Python only a year ago after being a long standing fan of C/C++ (and Matlab, for research).
Updated on July 19, 2020Comments
-
Nik almost 4 years
I want to use Java 8 tricks to do the following in one line.
Given this object definition:
@Getter @Setter @NoArgsConstructor @AllArgsConstructor public class MyObj { private String id; private Double value; }
and a
List<MyObj> objects
, I want to get aList<String> objectIds
which is a list of allid
s of the objects in the first list - in the same order.I can do this using a loop in Java but I believe there should be a one-liner lambda in Java8 that can do this. I was not able to find a solution online. Perhaps I wasn't using the right search terms.
Could someone suggest a lambda or another one-liner for this transform?
-
Nik about 7 yearsI am first ordering the list in descending order of
value
usingobjects.sort((o1, o2) -> (int) (o1.getValue()-o2.getValue()))
. I then need to extract only the objectIds to pass into another function without changing the order. If this method does not guarantee order, then I can't risk using it. -
xiumeteo about 7 yearsPer this stackoverflow.com/a/29218074/539864 it seems that in lists order is guaranteed
-
Louis Wasserman about 7 years@Nik that comparator is better written
objects.sort(Comparator.comparingInt(MyObj::getValue))
. But yes, order is guaranteed. -
Nik about 7 years@LouisWasserman: thanks. I always used to wonder why there isn't a much better comparator available for
double
s. Will use this henceforth in all my sorts. -
Nik about 7 years@LouisWasserman: Follow-up. How can I ensure descending order sort in that comparator? I believe by default it would be sorting in ascending order, right?
-
Louis Wasserman about 7 years
comparingInt(MyObj::getValue()).reversed()