Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use java8 lambda and function in scala

Tags:

java-8

scala

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?

like image 864
xmcx Avatar asked Jul 18 '26 03:07

xmcx


2 Answers

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

like image 118
Dmytro Mitin Avatar answered Jul 19 '26 19:07

Dmytro Mitin


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)
like image 37
Raman Mishra Avatar answered Jul 19 '26 19:07

Raman Mishra