package mightypork.utils.objects; import java.util.*; import java.util.Map.Entry; /** * Object utils class * * @author MightyPork */ public class ObjectUtils { public static Object fallback(Object... options) { for (Object o : options) { if (o != null) return o; } return null; // error } /** * Sort a map by keys, maintaining key-value pairs. * * @param map map to be sorted * @param comparator a comparator, or null for natural ordering * @return linked hash map with sorted entries */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static Map sortByKeys(Map map, final Comparator comparator) { List keys = new LinkedList(map.keySet()); if (comparator == null) { Collections.sort(keys); } else { Collections.sort(keys, comparator); } // LinkedHashMap will keep the keys in the order they are inserted // which is currently sorted on natural ordering Map sortedMap = new LinkedHashMap(); for (K key : keys) { sortedMap.put(key, map.get(key)); } return sortedMap; } /** * Sort a map by values, maintaining key-value pairs. * * @param map map to be sorted * @param comparator a comparator, or null for natural ordering * @return linked hash map with sorted entries */ @SuppressWarnings("rawtypes") public static Map sortByValues(Map map, final Comparator comparator) { List> entries = new LinkedList>(map.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Entry o1, Entry o2) { if (comparator == null) return o1.getValue().compareTo(o2.getValue()); return comparator.compare(o1.getValue(), o2.getValue()); } }); // LinkedHashMap will keep the keys in the order they are inserted // which is currently sorted on natural ordering Map sortedMap = new LinkedHashMap(); for (Map.Entry entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } public static String arrayToString(Object[] arr) { StringBuilder sb = new StringBuilder(); sb.append('['); boolean first = true; for (Object o : arr) { if (!first) sb.append(','); sb.append(o.toString()); } sb.append(']'); return sb.toString(); } public static List arrayToList(T[] objs) { ArrayList list = new ArrayList(); for (T o : objs) { list.add(o); } return list; } }