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);
}
}

Advertisements
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.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: