Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 s + " : " + Collections.frequency(colors, s);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading