3
votes

I have a code like this:

public class A {

    private String id;
    //constructor, getter, setter

}

In java I can use this:

public class C {

    @Test
    public void t() {
        List<A> list = Arrays.asList(new A("1"));
        list.sort(Comparator.comparing(A::getId));
        Map<String, List<A>> map = list.stream().collect(Collectors.groupingBy(A::getId));
    }
}

Here is scala(2.12) test:

class B {

  @Test
  def t(): Unit = {
    val list = util.Arrays.asList(new A("1"))
    list.sort(Comparator.comparing(a => a.getId))
    list.stream().collect(Collectors.groupingBy(a => a.getId))
  }

}

But in scala test, list.sort(Comparator.comparing(a => a.getId)) will get two errors:

  1. Error:(21, 26) inferred type arguments [com.test.A,?0] do not conform to method comparing's type parameter bounds [T,U <: Comparable[_ >: U]]

  2. Error:(21, 38) type mismatch; found : java.util.function.Function[com.test.A,String] required: java.util.function.Function[_ >: T, _ <: U]

and list.stream().collect(Collectors.groupingBy(a => a.getId)) will get this error:

  1. Error:(22, 49) missing parameter type

How can I use it?

2
list.sortBy( _.id).groupBy( _.id) what's wrong with this?Raman Mishra
I only consider completing it by means of java.util.List, but how to convert to java.util.Map<K, java.util.List> after groupBy.西门吹雪
I hope you have heard about javaConvertors in Decorate package there you will get a method asJava so I will get converted into the java MapRaman Mishra
Yes, I know, but I feel that it is not convenient to make multiple conversions. list -> asScala -> asJava ...西门吹雪
1. Provide exact error messages; 2. Are you using Scala 2.12? 3. Are you using Scala List or Java one in Scala?Alexey Romanov

2 Answers

2
votes

Try

import scala.compat.java8.FunctionConverters._

val list = util.Arrays.asList(new A("1"))
list.sort(Comparator.comparing[A, String](((a: A) => a.getId).asJava))
list.stream().collect(Collectors.groupingBy[A, String](a => a.getId))

libraryDependencies += "org.scala-lang.modules" %% "scala-java8-compat" % "0.9.0"

How to use Java lambdas in Scala

2
votes

One liner should be something like this to sort the list by id and then group them by id, the map is not an ordered data structure, so the order of your id's can be in any order. What you can do is first group them and then sort Map by key which is id in this case.

case class A(id:String)
val list = List(A("1"), A("2"), A("4"), A("3"))
list.sortBy(_.id).groupBy(_.id)