2

I'm working in Java. I need to convert a Seq<String> returned from a Scala method in Apache Kafka to a Java List<String> for processing.

I've found a method that can do the trick, seqAsJavaList, in the scala.collection.convert.WrapAsJava class.

https://www.garysieling.com/scaladoc/scala.collection.convert.wrapasjava/2016/02/15/scala__collection_convert_WrapAsJava.html

I've also found a StackOverflow query that's been helpful.

Convert from scala.collection.Seq<String> to java.util.List<String> in Java code

However, when I try the following code -

public static void listTopics ()
{
    ZkClient zkClient = connectToZookeeper();
    ZkUtils zkUtils = zookeeperUtility(zkClient);

    List<String> brokerTopics = WrapAsJava.seqAsJavaList(zkUtils.getAllTopics());

    zkClient.close();
}

I get the compiler error that non-static method seqAsJavaList cannot be referenced from a static context.

I can't instantiate WrapAsJava, so I have no idea how I could create a non-static context here.

The StackOverflow query had an answer with this code snippet.

import scala.collection.convert.WrapAsJava;

public class Test {
java.util.List<String> convert(scala.collection.Seq<String> seq) {
    return WrapAsJava.seqAsJavaList(seq);
}
}

Sadly, it raises the same error. How can I fix this? Thank you!

(Here is the method zkUtils.getAllTopics())

  def getAllTopics(zkClient: ZkClient): Seq[String] = {
val topics = ZkUtils.getChildrenParentMayNotExist(zkClient, BrokerTopicsPath)
if(topics == null)
  Seq.empty[String]
else
  topics
}
Community
  • 1
  • 1

1 Answers1

4

You can use scala.collection.JavaConversions:

import scala.collection.JavaConversions;
import scala.collection.immutable.Seq;

Seq<String> strings = ... //
List<String> javaList = JavaConversions.seqAsJavaList(strings);
marcospereira
  • 12,045
  • 3
  • 46
  • 52