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.

  • This question might help https://stackoverflow.com/questions/46107772/convert-scala-seq-to-java-list – Marc Jul 09 '20 at 05:21

1 Answers1

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);
Praphull
  • 21
  • 3
  • 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 – gourav bhattacharya Jul 09 '20 at 10:12