Functionals 4 Java

Filter, Map and Reduce before Java 8!

View Examples »

Introduction

Inspired by functional programming, Java 8 will bring a whole variety of new features such as methods that work on collections in a pretty neat way. Alongside with that, some usage of lambdas will also be part of the Java language in the future.

This framework aims to introduce a set of methods that bring those collection operations to earlier versions of Java. Since Java does not support lambdas for the time being, an interface has to be implemented by the user for each of the methods however.


Examples

Reduce

Calculare the sum of all elements in a collection using the reduce method:

import ch.rethab.functionals.*;

List<Integer> numbers = Arrays.asList(new Integer[]{1, 2, 3});
Integer sum = Functionals.reduce(new ReduceFunction<Integer>() {
	@Override
	public Integer reduce(Integer a, Integer b) {
		return a + b;
	}
}, numbers);

// sum = 6

Filter

Filter a collection of integers so that it only contains the even ones using the filter method:

import ch.rethab.functionals.*;

List<Integer> numbers;
numbers = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6 });
Collection<Integer> evenNumbers = Functionals.filter(new FilterFunction<Integer>() {
	@Override
	public boolean accept(Integer element) {
		return element % 2 == 0;
	}

}, numbers);
	 
// evenNumbers = [2, 4, 6]

Map

Apply a certain method to each element of a collection to make a new one using the map method:

import ch.rethab.functionals.*;

List<Integer> numbers = Arrays.asList(new Integer[]{ 1, 2, 3 });
MapFunction<Integer, String> mapFunction = 
	new MapFunction<Integer, String>() {
		@Override
		public String apply(Integer number) {
			switch (number) {
				case 1: return "one";
				case 2: return "two";
				case 3: return "three";
				default: return "out of range";
			}
		}
	};

List<String> namesOfNumbers;
namesOfNumbers = Functionals.map(mapFunction, numbers);

// namesOfNumbers = ["one", "two", "three"]

HTML Javadoc

Version 0.1
Link (new page)

About

This piece of free software is issued under the GNU Lesser General Public License LGPL.
Copyright © by Reto Habluetzel, 2011. Contact: f4j at rethab dot ch
The project is hosted on github: https://github.com/rethab/Functionals4Java