in.ashwanthkumar.utils.collections.Iterables Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of my-java-utils Show documentation
Show all versions of my-java-utils Show documentation
My personal set of utils that I take along with my java projects.
package in.ashwanthkumar.utils.collections;
import in.ashwanthkumar.utils.func.Function;
import in.ashwanthkumar.utils.func.Predicate;
import in.ashwanthkumar.utils.lang.option.Option;
import in.ashwanthkumar.utils.lang.tuple.Tuple2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import static in.ashwanthkumar.utils.lang.option.Option.option;
public class Iterables {
public static boolean exists(Iterable input, Predicate condition) {
for (T data : input) {
if (condition.apply(data)) return true;
}
return false;
}
public static boolean forall(Iterable input, Predicate condition) {
for (T data : input) {
if (!condition.apply(data)) return false;
}
return true;
}
public static T head(Iterable iterable) {
return iterable.iterator().next();
}
public static Option headOption(Iterable list) {
Iterator iterator = list.iterator();
if(iterator.hasNext()) return option(iterator.next());
else return option(null);
}
public static boolean isEmpty(Iterable list) {
return list == null || !list.iterator().hasNext();
}
public static boolean nonEmpty(Iterable list) {
return !isEmpty(list);
}
public static Map toMap(Iterable> tuples) {
HashMap map = new HashMap();
for (Tuple2 tuple : tuples) {
map.put(tuple._1(), tuple._2());
}
return map;
}
public static void foreach(Iterable input, Function condition) {
for (T data : input) {
condition.apply(data);
}
}
}