An another choice is here for Java 6+
interfaces:
interface TransformRule {
Out extract(In obj);
}
interface FilterRule {
boolean apply(T obj);
}
And Java8Stream-like container class for Collection/Map:
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
class FPMapContainer extends FPContainer
Now you can use it like Java8Stream in this way:
TransformRule integerStringTransform = new TransformRule() {
@Override
public String extract(Integer obj) {
return "" + obj;
}
};
TransformRule, String> collectionStringTransform = new TransformRule, String>() {
@Override
public String extract(Collection obj) {
String result = "";
for (String item : obj) {
result += item;
}
return result;
}
};
FilterRule ltFourFilter = new FilterRule() {
@Override
public boolean apply(Integer obj) {
return obj != null && obj < 4;
}
};
// ==============================================
String reduced;
// Collection case:
// `reduced` would be "123"
reduced = FPContainer.from(Arrays.asList(1, 4))
.concat(FPContainer.from(Arrays.asList(2)))
.concat(Arrays.asList(3))
.filter(ltFourFilter)
.map(integerStringTransform).reduce(collectionStringTransform);
// Map case:
reduced = FPContainer.from(stringIntegerHashMap)
.filter(new FilterRule>() {
@Override
public boolean apply(Map.Entry obj) {
return obj.getKey().charAt(0) < 'c' && obj.getValue() < 4;
}
})
.map(new TransformRule, String>() {
@Override
public String extract(Map.Entry obj) {
return ""+obj.getValue();
}
}).reduce(new TransformRule, String>() {
@Override
public String extract(Map obj) {
String result = "";
Map objectStringMap = sortByValue(obj);
for (Map.Entry entry : objectStringMap.entrySet()) {
result += entry.getKey().toString() + entry.getValue();
}
return result;
}
});
P.S.
sortByValue(map) is here: (credit: https://stackoverflow.com/a/109389/2293635)
public static Map sortByValue(Map map) {
List> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator