How to convert the following scala to java code?
for {
x <- List(1, 2)
y <- List(3, 4)
} yield (x, y)
Is it possible? what is yield?
I guess it's possible to convert any scala code to java...
@Tim already explained what is for..yield.
The Java code to do the same would be:
// Java doesn't have tuples, create your own type
record Pair(int x, int y) {}
List<Pair> result =
List.of(1, 2)
.stream()
.flatMap(x -> List.of(3, 4)
.stream()
.map(y -> new Pair(x, y))
)
.toList();
IMHO this is a great example of the conciceness and exprenessiveness of Scala, especially when working with collections.
Stream.of(1,2) instead of List.of(1,2).stream()..collect(Collectors.toList()); can be replaced by toList(); in newer versions of Java (v 21 here).Lists. Regarding using a list to represent a pair, it sounds quite unsafe to me, a record is a great fit as it can also be destructured in pattern matching in recent Java version I believe.You need to read up on this, but for is just syntactic sugar that is converted to map, flatMap, filter, and foreach calls.
Your for statement
for {
x <- List(1, 2)
y <- List(3, 4)
} yield (x, y)
becomes
List(1,2).flatMap(x => List(3,4).map(y => (x, y)))
This is just function calls which can easily be converted to Java.
map? Does this produce a map of the pairs (1,3), (2,4)?map is for transforming each item of the input to something else. Pretty sure it exists also in Java on Streams. Here List(3, 4).map(..) returns List((x,3),(x,4)), so a list of pairs. Then the flatMap does that for each x and flatten the list of lists into a list. End result is the list of all pairs (1,3),(1,4),(2,3),(2,4).All the existing replies are spot on, but I wanted to give a slightly different perspective on how to translate that into imperative Java code:
record Pair(int x, int y) {}
var yielded = new ArrayList<Pair>();
for (var x: List.of(1, 2)) {
for (var y: List.of(3, 4)) {
yielded.add(new Pair(x, y));
}
}
I'm not necessarily suggesting to do any of this, but maybe it can help people with no prior exposure to functional programming match Scala for-comprehensions with their experience.
for..yield from Scala for someone that is used to imperative code. I had never really thought of it this way :)