/java/

Java8 – Double colon operator

2015-01-09 00:44:58

Few examples how we can use double colon operator in java.

import common.Animal;
import common.NoeShip;

import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List

<animal> animals = NoeShip.getAnimals();

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

        animals.forEach(Main::log);

        animals.forEach(Animal::showDetails);

        System.out.println( animals.stream().map(a-&gt; a.getName()).collect(Collectors.toSet()) );
        System.out.println( animals.stream().map(Animal::getName).collect(Collectors.toSet()) );
    }

    private static void log(Animal animal) {
        System.out.println("From log:" + animal);
    }

}

NoeShip.java

package common;

import java.util.ArrayList;
import java.util.List;

public class NoeShip {
    public static List<animal> getAnimals() {
        List<animal> animals = new ArrayList&lt;&gt;();
        animals.add(new Animal("azor", "dog", Animal.COLOR.BROWN, Animal.SEX.MEN));
        animals.add(new Animal("wiz", "dog", Animal.COLOR.RED, Animal.SEX.FEMALE));
        animals.add(new Animal("mara", "cat", Animal.COLOR.GREY, Animal.SEX.FEMALE));
        animals.add(new Animal("nat", "cat", Animal.COLOR.BLACK, Animal.SEX.MEN));
        animals.add(new Animal("michal", "human", Animal.COLOR.WHITE, Animal.SEX.MEN));
        animals.add(new Animal("cola", "bird", Animal.COLOR.BROWN, Animal.SEX.FEMALE));
        animals.add(new Animal("turtle", "tank", Animal.COLOR.GREEN, Animal.SEX.MEN));
        animals.add(new Animal("tirla", "pika", Animal.COLOR.GREEN, Animal.SEX.FEMALE));
        return animals;
    }
}

Animal.java

package common;

public class Animal {

    public enum COLOR {WHITE, YELLOW, RED, BROWN, GREY, GREEN, BLACK}

    public enum SEX {MEN, FEMALE}

    private String name;
    private String species;
    private COLOR color;
    private SEX sex;

    public Animal() {
    }

    public Animal(String name, String species, COLOR color, SEX sex) {
        this.name = name;
        this.species = species;
        this.color = color;
        this.sex = sex;
    }

    //get &amp; set

    public static void showDetails(Animal animal) {
        System.out.println("Details: " + animal);
    }

    @Override
    public String toString() {
        return "Animal{" +
                "name='" + name + '\'' +
                ", species='" + species + '\'' +
                ", color=" + color +
                ", sex=" + sex +
                '}';
    }
}