Java8 Transform list of object to list of one attribute of object

24,658

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.

Share:
24,658
Nik
Author by

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, 2020

Comments

  • Nik
    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 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?

  • Nik
    Nik about 7 years
    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.
  • xiumeteo
    xiumeteo about 7 years
    Per this stackoverflow.com/a/29218074/539864 it seems that in lists order is guaranteed
  • Louis Wasserman
    Louis Wasserman about 7 years
    @Nik that comparator is better written objects.sort(Comparator.comparingInt(MyObj::getValue)). But yes, order is guaranteed.
  • Nik
    Nik about 7 years
    @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.
  • Nik
    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
    Louis Wasserman about 7 years
    comparingInt(MyObj::getValue()).reversed()