0

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...

3 Answers 3

5

@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.

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

8 Comments

Thank you! I didn't know the Java equivalent. I have also learned where rust gets its "functional" coding style from. And, yes, Scala is SO much more clear and expressive.
You could make this a bit more concise by using Stream.of(1,2) instead of List.of(1,2).stream().
Finally .collect(Collectors.toList()); can be replaced by toList(); in newer versions of Java (v 21 here).
I assumed the inputs are two 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.
I just wanted to point out one important difference between the Scala Collections API and the Java Streams API: the latter is always lazy for intermediate operations (like map and flatMap), the former requires a little bit extra to make it so: docs.scala-lang.org/overviews/collections-2.13/views.html
|
4

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.

2 Comments

I don't about "easily." What going on with map? Does this produce a map of the pairs (1,3), (2,4)?
@markspace 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).
1

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.

1 Comment

This is actually a great "mapping" of the for..yield from Scala for someone that is used to imperative code. I had never really thought of it this way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.