Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...