What does it mean :: in java?

2

Looking for how to sort a list of objects by a parameter I found this solution:

lista.sort(
    Comparator.comparing(EntradaLoteVo::getFechaRecepcionLote)
       .thenComparingInt(EntradaLoteVo::getId));

And I'm struck by this: EntradaLoteVo::getFechaRecepcionLote . Is it a lambda expression? I have not been able to find explanations on the internet because I do not know what it's called. I think it returns the value I have in the list that corresponds to the class EntradaLoteVo and executes the operation getFechaRecepcionLote for each element and then sort orders it. But what else can you do?

    
asked by Angel 04.10.2017 в 17:29
source

1 answer

3

:: is called Method Reference. It was introduced in Java 8.

For a long time, interfaces were used as callbacks for asynchronous processes, such as when you wanted to have the server response or when you wanted to create a new thread:

new Thread(new Runnable{
  @Override
  public void run()
  {
    // se ejecuta el callback
  }
}).run();

Now you can do something similar by sending the references of the methods to use them as callbacks and avoid such complex syntax:

public void LoginUsuario(String usuario, String pass, Consumer<bool,String> loginCallback)
{
   // logeamos usuarios con el servido..
   //
    boolean usuarioValido = true;
    String token = "adsfasdfadf";
    loginCallback.apply(usuarioValido, token);
}

loginUsuario("einer","123", (valido, token) -> {
   // vlidamos si es valido
});

(valido, token) -> {} is a valid method that translated would be:

public void callback_respuesta(boolean valido, String token)
{
   // validamos respuesta
}

That adapting it to your question would be:

loginUsuario("einer","123",  clasedelMetodo::callback_respuesta);

What this does is send the method reference callback_respuesta to the method loginUsuario .

This is called lambda functions. There are 3 types that are: Function , Supplier and Consummer . It is good to note that in the end the 3 are interfaces that is a trick that the compiler does to accept that kind of syntax.

This is the same as the Func<T, T1, T2.., TResult> and < a href="https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx"> Action<T, T2...> of C #.

    
answered by 04.10.2017 / 17:48
source