16

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?

4
  • the search terms for this is not 'lambda' but 'stream api'. lots of answers in that vein here. Commented Feb 17, 2017 at 19:05
  • 1
    What are all these annotations? Getter? Setter? Commented Feb 17, 2017 at 19:05
  • 1
    Is that from Lombok? Commented Feb 17, 2017 at 19:08
  • 1
    @user2357112: that's Lombok's annotation. Pretty common these days. Commented Feb 17, 2017 at 19:14

1 Answer 1

35

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
Per this stackoverflow.com/a/29218074/539864 it seems that in lists order is guaranteed
@Nik that comparator is better written objects.sort(Comparator.comparingInt(MyObj::getValue)). But yes, order is guaranteed.
@LouisWasserman: thanks. I always used to wonder why there isn't a much better comparator available for doubles. Will use this henceforth in all my sorts.
comparingInt(MyObj::getValue()).reversed()
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.