All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.onetwo.common.utils.CUtils Maven / Gradle / Ivy

There is a newer version: 4.7.2
Show newest version
package org.onetwo.common.utils;

import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.RandomAccess;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.onetwo.common.reflect.ReflectUtils;
import org.onetwo.common.utils.func.IndexableReturnableClosure;
import org.onetwo.common.utils.func.ReturnableClosure;
import org.onetwo.common.utils.list.JFishList;
import org.onetwo.common.utils.list.Predicate;
import org.onetwo.common.utils.map.BaseMap;
import org.onetwo.common.utils.map.CollectionMap;

import com.google.common.collect.Maps;

@SuppressWarnings({ "rawtypes", "unchecked" })
final public class CUtils {


	public static class NullOrEmtpyPredicate implements Predicate {

		private boolean result;

		public NullOrEmtpyPredicate(boolean result) {
			this.result = result;
		}

		@Override
		public boolean apply(Object obj) {
			if (obj == null || (String.class.isAssignableFrom(obj.getClass()) && StringUtils.isBlank(obj.toString())))
				return result;
			return !result;
		}

	};

	public static NullOrEmtpyPredicate NullOrEmptyTrue = new NullOrEmtpyPredicate(true);

	public static NullOrEmtpyPredicate NullOrEmptyFalse = new NullOrEmtpyPredicate(false);
	
    public static final List NULL_LIST = new NullList();

    @SuppressWarnings("serial")
    public static class NullList extends AbstractList implements RandomAccess, Serializable {
    	
    	private NullList(){}
        public int size() {return 0;}

        public boolean contains(Object obj) {return false;}

        public Object get(int index) {
            return null;
        }

        // Preserves singleton property
        private Object readResolve() {
            return NULL_LIST;
        }
    }
    
    public static  Collection emptyIfNull(Collection col){
    	if(col==null)
    		return Collections.EMPTY_SET;
    	return col;
    }
    
	public static  Map subtract(Map first, Map map){
		return subtract(first, map, false);
	}
	
	public static  Map subtract(Map first, Map map, boolean modifyFirst){
		if(map==null || map.isEmpty())
			return first;
		Map rs = null;
		if(modifyFirst)
			rs = first;
		else{
			rs = newMap(first.getClass());
			rs.putAll(first);
		}
		for(Map.Entry entry : (Set>)map.entrySet()){
			rs.remove(entry.getKey());
		}
		return rs;
	}

	public static Map arrayIntoMap(Class mapClass, Object... params) {
		return arrayIntoMap(CUtils.newMap(mapClass), params);
	}
	
	public static  Map newMap(Class mapClass){
		if(mapClass==null)
			return new HashMap();
		return (Map)ReflectUtils.newInstance(mapClass);
	}
	

	public static  Map asMap(Object... params) {
		if(LangUtils.isEmpty(params))
			return Collections.emptyMap();
		Map map = arrayIntoMap(CUtils.newHashMap(-1), params);
		return map;
	}
	
	public static  Map typeMap(T... params) {
		if(LangUtils.isEmpty(params))
			return Collections.emptyMap();
		Map map = arrayIntoMap(CUtils.newHashMap(-1), params);
		return map;
	}


	public static Map fromProperties(Object obj) {
		return ReflectUtils.toMap(obj);
	}
	
	public static BaseMap toBase(Map map) {
		if(map instanceof BaseMap)
			return (BaseMap) map;
		if(map!=null)
			return new BaseMap(map);
		else
			return null;
	}
	
	public static  T arrayIntoMap(T properties, Object... params) {
		if (params.length % 2 == 1)
			throw new IllegalArgumentException("参数不是key, value形式! ");

		int index = 0;
		Object name = null;
		for (Object s : params) {
			if (index % 2 == 0) {
				if (s == null || (String.class.isInstance(s) && StringUtils.isBlank(s.toString())))
					throw new IllegalArgumentException("字段名称不能为空! ");
				name = s;
			} else {
				properties.put(name, s);
			}
			index++;
		}
		
		return properties;
	}
	
	public static LinkedHashMap asLinkedMap(Object...params){
		return CUtils.arrayIntoMap(CUtils.newLinkedHashMap(), params);
	}

	public static  List newArrayList(){
		return newArrayList(-1);
	}
	
	public static  List newArrayList(int size){
		ArrayList list = null;
		if(size<=0)
			list = new ArrayList();
		else
			list = new ArrayList(size);
		return list;
	}
	
	public static  List newList(T...objs){
		ArrayList list = new ArrayList(Arrays.asList(objs));
		return list;
	}
	
	public static  T[] newArray(T...objs){
		return objs;
	}

	public static  HashSet newHashSet(){
		return new HashSet();
	}

	public static  HashSet asSet(T...objs){
		HashSet set = new HashSet();
		for(T obj : objs){
			set.add(obj);
		}
		return set;
	}

	public static  HashSet newHashSet(int size){
		HashSet sets = null;
		if(size<=0)
			sets = new HashSet();
		else
			sets = new HashSet(size);
		return sets;
	}
	public static  TreeSet newTreeSet(){
		return new TreeSet();
	}

	public static  Map newMap(){
		return newHashMap(-1);
	}

	public static  Map newHashMap(int size){
		if(size<=0)
			return new HashMap();
		return new HashMap(size);
	}

	public static  CollectionMap newListMap(int size){
		if(size<=0)
			return CollectionMap.newListMap();
		return CollectionMap.newListMap(size);
	}

	public static  LinkedHashMap newLinkedHashMap(int size){
		if(size<=0)
			return new LinkedHashMap();
		return new LinkedHashMap(size);
	}

	public static  LinkedHashMap newLinkedHashMap(){
		return new LinkedHashMap();
	}

	public static  List trimAsList(T... array) {
		return tolist(array, true);
	}
	public static  List asList(T... array) {
		return tolist(array, false);
	}
	public static List tolist(Object object, boolean trimNull) {
		return tolist(object, trimNull, NULL_LIST);
	}

	public static  Collection toCollection(Object object) {
		if(object==null)
			return Collections.EMPTY_LIST;
		List list = null;
		if (Collection.class.isAssignableFrom(object.getClass())) {
			return (Collection)object;
		} else if (object.getClass().isArray()) {
			int length = Array.getLength(object);
			list = new ArrayList(length);
			appendToList(object, list);
		} else {
			list = new ArrayList(5);
			list.add(object);
		}
		return list;
	}

	public static List tolist(Object object, boolean trimNull, List def) {
		if (object == null)
			return def;
		List list = null;
		if (List.class.isInstance(object)) {
			list = (List) object;
		} else if(Iterable.class.isInstance(object)){
			list = new ArrayList();
			for(Object obj : (Iterable)object){
				list.add(obj);
			}
		}else if (object.getClass().isArray()) {
			int length = Array.getLength(object);
			list = new ArrayList(length);
//			appendToList(object, list);
			for (int i = 0; i < length; i++) {
				list.add(Array.get(object, i));
			}
		} else {
			list = new ArrayList(5);
			list.add(object);
		}
		if (trimNull)
			stripNull(list);
		return (list == null || list.isEmpty()) ? def : list;
	}
	
	public static void appendToList(Object object, List list){
		int length = Array.getLength(object);
		Object o = null;
		for(int i=0; i List trimAndexcludeTheClassElement(boolean trimNull, Object array, Object... excludeClasses) {//Class... excludeClasses
		if (array == null)
			return NULL_LIST;
		
		List list = null;
		if(array.getClass().isArray()){
			int length = Array.getLength(array);
			list = new ArrayList(length);
			for (int i = 0; i < length; i++) {
				list.add(Array.get(array, i));
			}
		}else
			list = tolist(array, trimNull);
		
		if (excludeClasses!=null && excludeClasses.length>0)
			strip(list, (Object[]) excludeClasses);
		return (list == null) ? NULL_LIST : list;
	}
	
	/****
	 * remove specify value frome list
	 * default remove null or blank string
	 * @param collection
	 * @param stripValue
	 * @return
	 */
	public static Collection strip(Collection collection, final Object... stripValue) {
		collection.removeIf(obj-> {

				if (obj instanceof Class) {
					if (ArrayUtils.isAssignableFrom(stripValue, (Class) obj))
						return true;
				} else if (obj == null || (String.class.isAssignableFrom(obj.getClass()) && StringUtils.isBlank(obj.toString())) || ArrayUtils.contains(stripValue, obj)){
					return true;
				}
				return false;
			
		});
		return collection;
		
	}
	
	public static Object[] asArray(Object obj) {
		if(obj.getClass().isArray()){
			return (Object[]) obj;
		}else if(Collection.class.isAssignableFrom(obj.getClass())){
			Collection col = (Collection) obj;
			Object[] array = new Object[col.size()];
			int i = 0;
			for (Object o : col) {
				array[i++] = o;
			}
			return array;
		}else{
			return new Object[]{obj};
		}
	}
	
	public static String[] asStringArray(Object obj) {
		if(obj.getClass().isArray()){
			if(obj.getClass().getComponentType()==String.class){
				return (String[]) obj;
			}else{
				Object[] objArray = (Object[]) obj;
				String[] strs = new String[objArray.length];
				int index = 0;
				for(Object o : objArray){
					strs[index++] = o.toString();
				}
				return strs;
			}
		}else if(Collection.class.isAssignableFrom(obj.getClass())){
			Collection col = (Collection) obj;
			String[] strs = new String[col.size()];
			int i = 0;
			for (Object o : col) {
				strs[i++] = o.toString();
			}
			return strs;
		}else if(Iterable.class.isAssignableFrom(obj.getClass())){
			List list = LangUtils.newArrayList();
			for (Object o : (Iterable) obj) {
				list.add(o.toString());
			}
			return list.toArray(new String[0]);
		}else{
			return new String[]{obj.toString()};
		}
	}
	
	public static Object[] map2Array(Map map){
		Object[] array = new Object[map.size()*2];
		int index = 0;
		for(Entry entry : map.entrySet()){
			array[index++] = entry.getKey();
			array[index++] = entry.getValue();
		}
		return array;
	}
	
	public static  Map> groupBy(Collection datas, ReturnableClosure block){
		return JFishList.wrap(datas).groupBy(block);
	}
	
    public static  void filter(Collection collection, Predicate predicate) {
    	CollectionUtils.filter(collection, predicate);
    }
	
    public static  void filter(Map map, Predicate> predicate) {
    	if (map != null && predicate != null) {
            for (Iterator> it = map.entrySet().iterator(); it.hasNext();) {
                if (predicate.apply(it.next()) == false) {
                    it.remove();
                }
            }
        }
    }
	
    /*****
     * list1中存在,list2中找不到的元素
     * @param list1
     * @param list2
     * @param notInPredicate
     */
    public static  List difference(List list1, List list2, NotInPredicate notInPredicate) {
    	List diff = LangUtils.newArrayList();
    	for(T e : list1){
    		if(notInPredicate.apply(e, list2))
    			diff.add(e);
    	}
       return Collections.unmodifiableList(diff);
    }
    /****
     * 
     * list1中存在,list2中找不到的元素
     * @param list1
     * @param list2
     * @param properties
     * @return
     */
    public static  List difference(List list1, List list2, final String...properties) {
    	return difference(list1, list2, new NotInPredicate() {
			@Override
			public boolean apply(T e, List list) {
				return !contains(list, e, properties);
			}
		});
    }
	
	public static interface NotInPredicate {
		boolean apply(T e, List list);
	}
	
	public static interface EqualsPredicate {
		boolean apply(T e1, T e2);
	}
	
	public static  boolean containsAnyOne(Collection c, T...elements){
		Assert.notEmpty(elements);
		if(LangUtils.isEmpty(c))
			return false;
		for(T e : elements){
			if(c.contains(e))
				return true;
		}
		return false;
	}
	
	public static  boolean contains(Collection c, T element, EqualsPredicate equalsPredicate){
		if(LangUtils.isNotEmpty(c)){
			for(T e : c){
				if(equalsPredicate.apply(e, element))
					return true;
			}
		}
		return false;
	}
	
	public static  boolean contains(Collection c, T element, final String...properties){
		return contains(c, element, new EqualsPredicate(){
			@Override
			public boolean apply(T e1, T e2) {
				return isEquals(e1, e2, properties);
			}
		});
	}

	
	public static  boolean isEquals(T e1, T e2, EqualsPredicate equalsPredicate){
		return equalsPredicate.apply(e1, e2);
	}
	
	public static  boolean isEquals(final T e1, final T e2, final String...properties){
		if(e1==e2)
			return true;
		if(e1==null || e2==null)
			return false;
		return isEquals(e1, e2, new EqualsPredicate(){

			@Override
			public boolean apply(T e1, T e2) {
				for(String p : properties){
					if(!ReflectUtils.getPropertyValue(e1, p).equals(ReflectUtils.getPropertyValue(e2, p)))
						return false;
				}
				return true;
			}
			
		});
	}
	

	
	public static Map toMap(List list){
		return toMap(list, (e, index)->index);
	}
	
	public static  Map toMap(List list, IndexableReturnableClosure keyMap){
		Map map = Maps.newHashMap();
		int index = 0;
		for(Object e : list){
			K key = keyMap.execute(e, index);
			map.put(key, e);
			index++;
		}
		return map;
	}

	public static List toList(Map map) {
		if(map==null)
			return NULL_LIST;
		List list = new ArrayList(map.size()*2);
		for(Map.Entry entry : map.entrySet()){
			list.add(entry.getKey());
			list.add(entry.getValue());
		}
		return list;
	}

	public static  List map(Collection list, Function mapper){
		Assert.notNull(list);
		Assert.notNull(mapper);
		return list.stream().map(mapper).collect(Collectors.toList());
	}
	
	public static  List iterableToList(Iterable it){
		if(it==null)
			return Collections.EMPTY_LIST;
		/*List list = new ArrayList();
		it.forEach(e->list.add(e));
		return Collections.unmodifiableList(list);*/
		return StreamSupport.stream(it.spliterator(), false)
							.collect(Collectors.toList());
	}
	
	private CUtils(){
	}

}