Search code examples
javalambdajava-8

Lambda(->) to Double colon(::) method reference


here I'm trying to print values using lambda. Is it possible to make it in double colon way?

public class Occurance 
{
    static void occuranceUsingListSet()
    {
        ArrayList<String> listColors = new ArrayList<>(Arrays.asList("Red","blue","green","green"));
        Set<String> setVals = new LinkedHashSet<>(listColors);
        setVals.stream().forEach(s -> System.out.println(s + " : " + Collections.frequency(listColors, s)));
    }
    
}

setVals.stream().forEach(s -> System.out.println(s + " : " + Collections.frequency(listColors, s)));

Is there any possibilities to use double colon?

And is method reference and pass by reference are same?

I can see this double colon is pass method reference. But in this slack answer I can see that there is no such thing like pass by reference in java. https://stackoverflow.com/a/73021/11962586.


Solution

  • No, you cannot do that whole operation with a single method reference. You are doing more than a single method call in your lambda.

    Although, if you refactor your string creation into a new function, then you can use a method reference to call System.out.println:

    static void occuranceUsingListSet() {
        // You don't need to wrap Arrays.asList in a new ArrayList.
        List<String> listColors = Arrays.asList("Red","blue","green","green");
        Set<String> setVals = new LinkedHashSet<>(listColors);
    
        setVals.stream()
            .map(s -> createFrequencyString(s, listColors);
            .forEach(System.out::println);
    }
    
    static String createFrequencyString(String color, List<String> colors) {
        return color + " : " + Collections.frequency(colors, color);
    }