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
195 views
in Technique[技术] by (71.8m points)

Splitting Class into its Attributes in Lambda Expression in Java

Let's say you have a custom class:

public class T {
    int a;
    int b;
}

Is there a way you can split up the class in a lambda expression in the following way:

(Stream of T instances).forEach((a, b) -> {});
question from:https://stackoverflow.com/questions/65881572/splitting-class-into-its-attributes-in-lambda-expression-in-java

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

1 Answer

0 votes
by (71.8m points)

Java doesn't have the concept of tuples, so no! But there can be a workaround by converting the stream to a Map (which has a lot of limitations and consequences):

(Stream of T instances)
    .collect(Collectors.toMap(t -> t.a, t -> t.b))
    .forEach((a, b) -> {});

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

...