Home > Java > Java 8 : Double Colon operator

Java 8 : Double Colon operator

Double Colon operator introduced in Java 8, We use it as method reference.

Syntax : ClassName::MethodName

for example, if we want to print a list :


List<String> strings = Arrays.asList("one","two");

strings.forEach(System.out::println);

here forEach is a new method added to the List interface in java 8. System.out is the PrintStream Class and println is method in it.

Complete Example:


import java.util.*;
import java.util.stream.*;

public class DoubleColon{

public static void display(String name){
System.out.println("Name : "+name);
}
public static void main(String[] args){
List<String> names = Arrays.asList("one","two","three");
names.forEach(DoubleColon::display);
}
}

Categories: Java
  1. Miguel Munoz
    July 7, 2014 at 4:19 am

    This post leaves some big questions unanswered. How do I specify a method as a parameter? And how do I call that method? It would be very helpful to see the signature of the forEach() method. In fact, it would be helpful to see the full source code for the method.

  2. December 30, 2022 at 9:42 pm

    Very nnice post

  1. No trackbacks yet.

Leave a comment