Created
July 5, 2018 12:30
-
-
Save kunalvarma05/58ed5ee35bec4031db68df55c25702d7 to your computer and use it in GitHub Desktop.
Functional List demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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