functional programming in Java

前端 未结 5 992
滥情空心
滥情空心 2021-01-17 13:58

how can you emulate functional programming in java, specifically, doing things like map a function to a collection of items?

map(func, new String[]{\"a\",\"         


        
5条回答
  •  不思量自难忘°
    2021-01-17 14:46

    All attempts of functional programming will have some part of verbose and/or awkward to it in Java, until Java 8.

    The most direct way is to provide a Function interface (such as this one form Guava) and provide all kinds of methods that take and call it (such as Collections#transfrom() which does what I think your map() method should do).

    The bad thing about is that you need to implement Function and often do so with an anonymous inner class, which has a terribly verbose syntax:

    Collection result = Collections.transform(input, new Function() {
        public OutputType apply(InputType input) {
          return frobnicate(input);
        }
    });
    

    Lambda expressions (introduced in Java 8) make this considerably easier (and possibly faster). The equivalent code using lambdas looks like this:

    Collection result = Collections.transform(input, SomeClass::frobnicate);
    

    or the more verbose, but more flexible:

    Collection result = Collections.transform(input, in -> frobnicate(in));
    

提交回复
热议问题