15

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 a List<String> objectIds which is a list of all ids 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?

Stuart Marks
  • 127,867
  • 37
  • 205
  • 259
Nik
  • 5,515
  • 14
  • 49
  • 75

1 Answers1

34

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.

Gabe Gates
  • 902
  • 1
  • 14
  • 19
xiumeteo
  • 941
  • 7
  • 16
  • I am first ordering the list in descending order of `value` using `objects.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. – Nik Feb 17 '17 at 19:11
  • 1
    Per this http://stackoverflow.com/a/29218074/539864 it seems that in lists order is guaranteed – xiumeteo Feb 17 '17 at 19:16
  • 4
    @Nik that comparator is better written `objects.sort(Comparator.comparingInt(MyObj::getValue))`. But yes, order is guaranteed. – Louis Wasserman Feb 17 '17 at 19:17
  • @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 Feb 17 '17 at 19:22
  • @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? – Nik Feb 17 '17 at 19:26
  • 3
    `comparingInt(MyObj::getValue()).reversed()` – Louis Wasserman Feb 17 '17 at 20:46