Search code examples
javalambdastaticfinalpublic

public static final Lambda?


Is it considered good practice to group common lambda expressions in a utility class to avoid code duplication ?

What's the best way to do so ? Right now, I have a MathUtils class with a few public static final Functions members :

public class MathUtils{
    public static final Function<Long, Long> triangle = n -> n * (n + 1) / 2,
        pentagonal = n -> n * (3 * n - 1) / 2,
        hexagonal = n -> n * (2 * n - 1);
}

Solution

  • You could also do it this way

    public class MathUtils
    {
        public static long triangle(long n)
        {
            return n * (n + 1) / 2;
        }
    

    And use it like

        MathUtils::triangle 
    

    depending on your taste and use cases.