Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

functional programming in Java

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","b","c"});

what's the least verbose & awkward way to do it?

like image 583
user678070 Avatar asked May 11 '11 09:05

user678070


People also ask

What is functional programming in Java?

Functional programming involves crucial concepts such as immutable states, referential transparency, method references, high-order and pure functions. It involves programming techniques such as functional composition, recursion, currying and functional interfaces.

Can you use functional programming in Java?

Functional programming in Java 8Java 8 came with new additions like lambdas, streams, and functional interfaces which made for the possible implementation of functional programming techniques in Java and the implementation of the declarative style of programming in Java.

What is functional programming?

Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”.

What is the benefit of functional programming in Java?

The biggest benefit of Functional programming is brevity, because code can be more concise. A functional program doesn't create an iterator variable to be the center of a loop, so this and other kinds of overhead are eliminated from your code.


2 Answers

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<OutputType> result = Collections.transform(input, new Function<InputType,OutputType>() {
    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<OutputType> result = Collections.transform(input, SomeClass::frobnicate);

or the more verbose, but more flexible:

Collection<OutputType> result = Collections.transform(input, in -> frobnicate(in));
like image 94
Joachim Sauer Avatar answered Oct 06 '22 00:10

Joachim Sauer


I have used lambdaj and functionaljava for this sort of things. And there are probably others...

like image 26
Persimmonium Avatar answered Oct 05 '22 23:10

Persimmonium