Last active
January 18, 2018 22:47
-
-
Save ntreu14/a5301d0715c4ead2156e7fe7b444ba31 to your computer and use it in GitHub Desktop.
Implementing fold and reduce in Java
This file contains 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
import java.util.function.BiFunction; | |
import java.util.List; | |
import java.util.Arrays; | |
public class FunctionsExample { | |
public static void main(String[] args) { | |
String[] strs = {"Example", "Strings", "To", "Join"}; | |
List<String> strsList = Arrays.asList(strs); | |
BiFunction<String, String, String> concat = (str1, str2) -> str1 + str2; | |
final String EMPTY_STRING = ""; | |
System.out.println(reduce(concat, strsList)); | |
System.out.println(fold(concat, EMPTY_STRING, strsList)); | |
} | |
static <T> T reduce(BiFunction<T, T, T> f, List<T> list) { | |
if (list == null || list.isEmpty()) { | |
throw new IllegalArgumentException("The list argument cannot be null or empty."); | |
} | |
T head = list.get(0); | |
List<T> rest = list.subList(1, list.size()); | |
return fold(f, head, rest); | |
} | |
static <State, T> State fold(BiFunction<State, T, State> f, State state, List<T> list) { | |
if (list == null || list.isEmpty()) { | |
return state; | |
} | |
T head = list.get(0); | |
List<T> rest = list.subList(1, list.size()); | |
return fold(f, f.apply(state, head), rest); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment