Preocupação: Java Promotion Camp , os artigos mais recentes serão entregues na primeira vez, materiais de aprendizado gratuitos de 10T podem ser coletados a qualquer momento! ! !
A operação de dois pontos duplos (: :), também conhecida como operador de referência do método, é usada para chamar diretamente o método da classe especificada. Seu comportamento é exatamente o mesmo que a expressão lambda. A única diferença entre ele e a expressão lambda é que ele usa o nome para se referir diretamente ao método, em vez de fornecer um delegado do método.
Sintaxe:
<Class name>::<method name>
Exemplo: Stream
Todos os elementos impressos :
- Use expressões Lambda:
stream.forEach(s-> System.out.println(s));
Exemplo completo:
// Java code to print the elements of Stream
// without using double colon operator
import java.util.stream.*;
class GFG {
public static void main(String[] args)
{
// Get the stream
Stream<String> stream
= Stream.of("Geeks", "For",
"Geeks", "A",
"Computer",
"Portal");
// Print the stream
stream.forEach(s -> System.out.println(s));
}
}
Saída:
Geeks
For
Geeks
A
Computer
Portal
- Use o operador dois pontos:
stream.forEach(System.out::println(s));
Exemplo completo:
// Java code to print the elements of Stream
// using double colon operator
import java.util.stream.*;
class GFG {
public static void main(String[] args)
{
// Get the stream
Stream<String> stream
= Stream.of("Geeks", "For",
"Geeks", "A",
"Computer",
"Portal");
// Print the stream
// using double colon operator
stream.forEach(System.out::println);
}
}
Saída:
Geeks
For
Geeks
A
Computer
Portal
Quando e como usar o operador de dois pontos?
A referência do método ou o operador de dois pontos duplo pode ser usado nos seguintes métodos:
- Método estático
- Método de instância
- Construtor
Como usar referências de método em Java:
- Método estático
Sintaxe:
(ClassName::methodName)
Exemplos:
SomeClass::someStaticMethod
Exemplo completo:
// Java code to show use of double colon operator
// for static methods
import java.util.*;
class GFG {
// static function to be called
static void someFunction(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Geeks");
list.add("For");
list.add("GEEKS");
// call the static method
// using double colon operator
list.forEach(GFG::someFunction);
}
}
Saída:
Geeks
For
GEEKS
- Método de instância
Sintaxe:
(objectOfClass::methodName)
Exemplos:
System.out::println
Exemplo completo:
// Java code to show use of double colon operator
// for instance methods
import java.util.*;
class GFG {
// instance function to be called
void someFunction(String s)
{
System.out.println(s);
}
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Geeks");
list.add("For");
list.add("GEEKS");
// call the instance method
// using double colon operator
list.forEach((new GFG())::someFunction);
}
}
Saída:
Geeks
For
GEEKS
- Método pai
Sintaxe:
(super :: methodName)
Exemplos:
super::someSuperClassMethod
Exemplo completo:
// Java code to show use of double colon operator
// for super methods
import java.util.*;
import java.util.function.*;
class Test {
// super function to be called
String print(String str)
{
return ("Hello " + str + "\n");
}
}
class GFG extends Test {
// instance method to override super method
@Override
String print(String s)
{
// call the super method
// using double colon operator
Function<String, String> func = super::print;
String newValue = func.apply(s);
newValue += "Bye " + s + "\n";
System.out.println(newValue);
return newValue;
}
// Driver code
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Geeks");
list.add("For");
list.add("GEEKS");
// call the instance method
// using double colon operator
list.forEach(new GFG()::print);
}
}
Saída:
Hello Geeks
Bye Geeks
Hello For
Bye For
Hello GEEKS
Bye GEEKS
- Métodos de instância para tipos específicos de objetos
Sintaxe:
(ClassName::methodName)
Exemplos:
SomeClass::someInstanceMethod
Exemplo completo:
// Java code to show use of double colon operator
// for instance method of arbitrary type
import java.util.*;
class Test {
String str=null;
Test(String s)
{
this.str=s;
}
// instance function to be called
void someFunction()
{
System.out.println(this.str);
}
}
class GFG {
public static void main(String[] args)
{
List<Test> list = new ArrayList<Test>();
list.add(new Test("Geeks"));
list.add(new Test("For"));
list.add(new Test("GEEKS"));
// call the instance method
// using double colon operator
list.forEach(Test::someFunction);
}
}
Saída:
Geeks
For
GEEKS
- Construtor de classe
Sintaxe:
(ClassName::new)
Exemplos:
ArrayList::new
Exemplo completo:
// Java code to show use of double colon operator
// for class constructor
import java.util.*;
class GFG {
// Class constructor
public GFG(String s)
{
System.out.println("Hello " + s);
}
// Driver code
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Geeks");
list.add("For");
list.add("GEEKS");
// call the class constructor
// using double colon operator
list.forEach(GFG::new);
}
}
Saída:
Hello Geeks
Hello For
Hello GEEKS