0

Here are some lines of code that need to convert into Java.

val geojsonSeq = for (kml <- kmlSeq) yield kmlConverter.toGeoJson(kml)

I tried to convert using for each loop in java using lamda operator but not able to get it.

kmlSeq.foreach((Function1<Option<Kml>, U>) (f) -> {
            
        });

Every time I am getting compile-time error like: "The method foreach(Function1<Option,U>) is ambiguous for the type Seq<Option>"

Apart from this if I'm going to use normally for each loop in java like :

for(Option<Kml> kml : kmlSeq)
        {
            
        }

In that case kmlSeq is throwing error like : "Can only iterate over an array or an instance of java.lang.Iterable" But in scala the kmlSeq looping into Option object.

1

1 Answer 1

1

You can use either of two ways (Assuming return type of toGeoJson is String)

List<String> result = kmlSeq
  .stream()
  .flatMap(kmlOpt -> 
    kmlOpt.map(Stream::of).orElseGet(Stream::empty)
  )
  .map(kml -> kmlConverter.toGeoJson(kml))
  .collect(Collectors.toList());

or

List<String> result = kmlSeq
  .stream()
  .flatMap(kmlOpt -> 
    kmlOpt.map(kml ->
      Stream.of(kmlConverter.toGeoJson(kml))
    ).orElseGet(Stream::empty)
  )
  .collect(Collectors.toList());

To print, do this

result.forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Praphull thanks for providing the solution but I am getting an error on the .stream() method as "The method stream() is undefined for the type Seq<Option<Kml>>", Is there any alternatives for it.

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.