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
}

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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