Skip to content

Instantly share code, notes, and snippets.

@kunalvarma05
Created July 5, 2018 12:30
Show Gist options
  • Save kunalvarma05/58ed5ee35bec4031db68df55c25702d7 to your computer and use it in GitHub Desktop.
Save kunalvarma05/58ed5ee35bec4031db68df55c25702d7 to your computer and use it in GitHub Desktop.
Functional List demo
package com.foo.bar;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class App
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= 6; i++)
{
list.add(i);
}
FunctionalList<Integer> functionalList = new FunctionalList<Integer>(list);
Integer sum = functionalList
.filter(n -> n % 2 == 0)
.map(n -> n * 2)
.map(n -> {
System.out.println(n);
return n;
})
.reduce(0, (s, n) -> s + n);
System.out.println("Sum:" + sum);
}
}
class FunctionalList<T>
{
protected List<T> list;
public FunctionalList(List<T> list)
{
this.list = list;
}
public List<T> getList()
{
return this.list;
}
public FunctionalList<T> map(Function<T, T> func)
{
List<T> modifiedList = new ArrayList<T>();
for (T t : this.getList())
{
T ret = func.apply(t);
modifiedList.add(ret);
}
return new FunctionalList<T>(modifiedList);
}
public FunctionalList<T> filter(Function<T, Boolean> func)
{
List<T> modifiedList = new ArrayList<T>();
for (T t : this.getList())
{
if (func.apply(t))
{
modifiedList.add(t);
}
}
return new FunctionalList<T>(modifiedList);
}
public T reduce(T accumulator, AccumulatedFunction<T, T, T> func)
{
for (T t : this.getList())
{
accumulator = func.apply(accumulator, t);
}
return accumulator;
}
}
@FunctionalInterface
interface AccumulatedFunction<A, S, T>
{
T apply(A a, S s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment