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:
Error:(21, 26) inferred type arguments [com.test.A,?0] do not conform to method comparing's type parameter bounds [T,U <: Comparable[_ >: U]]
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:
How can I use it?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With