Biz工具类

package com.common.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.beanutils.BeanPropertyValueEqualsPredicate;
import org.apache.commons.beanutils.BeanToPropertyValueTransformer;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.PredicateUtils;
import org.apache.commons.collections.comparators.FixedOrderComparator;

import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimaps;

@SuppressWarnings("unchecked")
public class BizUtil {

  public static  Map listToMap(String keyName, List list) {
    Map map = Maps.newHashMap();
    if (CollectionUtils.isNotEmpty(list)) {
      for (V val : list) {
        try {
          PropertyDescriptor pd = new PropertyDescriptor(keyName,val.getClass());
          Method getMethod = pd.getReadMethod();// 获得get方法
          Object o = getMethod.invoke(val);// 执行get方法返回一个Object
          if (o != null) {
            map.put((K) o, val);
          }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
          e.printStackTrace();
        }
      }
    }
    return map;
  }

  // listToMap,1个key对应的是1个元素
  // listToMapList,1个key对应的是1个list。list中属性id一样的,放到1个小的list中。
  public static  Map> listToMapList(String keyName,List list) {
    ListMultimap multimap = ArrayListMultimap.create();
    if (CollectionUtils.isNotEmpty(list)) {
      for (V val : list) {
        try {
          PropertyDescriptor pd = new PropertyDescriptor(keyName,val.getClass());
          Method getMethod = pd.getReadMethod();// 获得get方法
          Object o = getMethod.invoke(val);// 执行get方法返回一个Object
          if (o != null) {
            multimap.put((K) o, val);
          }
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | IntrospectionException e) {
          e.printStackTrace();
        }
      }
    }
    return Multimaps.asMap(multimap);
  }

  /**
   * 把1个集合,转换成Map。用法示例:Map dictionaryMap =
   * BizUtil.listToMap("BIANMA", dictionarys);
   * 
   * @param keyName 集合元素唯一字段的名称
   * @param list 集合元素
   * @return map
   */
  // list中的key重复会报错,Google工具Map会检查“唯一性”,实际情况中就算重复了,不影响的,直接覆盖就好了嘛
  public static  Map listToMapMustUnique(final String keyName,List list) {
    if (CollectionUtils.isEmpty(list)) {
      return null;
    }
    Map map = Maps.uniqueIndex(list, new Function() {
      @Override
      public K apply(V v) {
        try {
          return (K) PropertyUtils.getSimpleProperty(v, keyName);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
          e.printStackTrace();
          return null;
        }
      }
    });
    return map;
  }

  /**
   * 
   * @Title: BeanToMap
   * @Description: bean转换成map
   * @param obj
   * @return map
   *
   */
  public static Map bean2Map(Object obj) {
    if (obj == null) {
      return null;
    }
    Map map = Maps.newHashMap();
    try {
      BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
      PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
      for (PropertyDescriptor property : propertyDescriptors) {
        String key = property.getName();
        // 过滤class属性
        if (!key.equalsIgnoreCase("class")) {
          // 得到property对应的getter方法
          Method getter = property.getReadMethod();
          Object value = getter.invoke(obj);
          map.put(key, value);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return map;
  }
  /**
   * 
   * @Title: MapFilter
   * @Description: map批量过滤key的值
   * @param map
   * @param keys
   * @return map
   *
   */
  public static Map MapFilter(Map map,List keys) {
    return Maps.filterKeys(map, Predicates.not(Predicates.in(keys)));
  }

  /**
   * 提取集合中的对象的一个属性, 组合成List.
   * 
   * @param collection 来源集合.
   * @param propertyName 要提取的属性名.
   */
  public static  List extractToList(final Collection collection,final String propertyName) {
    if (CollectionUtils.isEmpty(collection)) {
      return null;
    }
    List list = new ArrayList(collection.size());
    CollectionUtils.collect(collection, new BeanToPropertyValueTransformer(propertyName), list);
    return list;
  }

  /**
   * 提取集合中的对象的一个属性和属性值提取新的List
   * 
   * @param collection 来源集合
   * @param propertyName 要提取的属性名
   * @param propertyValue 要提取的属性名的值
   */
  public static  List extractToList(final Collection collection,final String propertyName,V propertyValue) {
    if (CollectionUtils.isEmpty(collection)) {
      return null;
    }
    List list = new ArrayList();
    CollectionUtils.select(collection, new BeanPropertyValueEqualsPredicate(propertyName,propertyValue), list);
    return list;
  }
  
  /**
   * 提取集合中的对象的一个属性的属性值在当前值集合中的对象列表
   * 
   * @param collection 来源集合
   * @param propertyName 要提取的属性名
   * @param propertyValues 要提取的属性名的值
   */
  public static  List extractToList(final Collection collection,final String propertyName,List propertyValues) {
    if (CollectionUtils.isEmpty(collection)) {
      return null;
    }
    List list = new ArrayList();
    List predicates = Lists.transform(propertyValues, new Function(){
      @Override
      public Predicate apply(V v) {
        return new BeanPropertyValueEqualsPredicate(propertyName,v);
      }
    });
    CollectionUtils.select(collection, PredicateUtils.anyPredicate(predicates), list);
    return list;
  }
  
  /**
   * 提取集合中的对象的一个属性的属性值不在当前值集合中的对象列表
   * 
   * @param collection 来源集合
   * @param propertyName 要提取的属性名
   * @param propertyValues 要提取的属性名的值
   */
  public static  List extractToReverseList(final Collection collection,final String propertyName,List propertyValues) {
    if (CollectionUtils.isEmpty(collection)) {
      return null;
    }
    List list = new ArrayList();
    List predicates = Lists.transform(propertyValues, new Function(){
      @Override
      public Predicate apply(V v) {
        return new BeanPropertyValueEqualsPredicate(propertyName,v);
      }
    });
    CollectionUtils.selectRejected(collection, PredicateUtils.anyPredicate(predicates), list);
    return list;
  }
  
  /**
   * id字符串转换为list
  * 
  * @param idStr id字符串
  * @param separator 切分符 {@linkplain com.buoumall.commonService.consts.Consts}
  * @return list
  *
   */
  public static List stringToLongList(String idStr, String separator) {
    List idList = Lists.newArrayList();
    String[] idArray = idStr.split(separator);
    if (idArray != null) {
      for (String id : idArray) {
        idList.add(Long.valueOf(id));
      }
    }
    return idList;
  }
  
  /**
   * id字符串转换为list并升序排列
  * 
  * @param idStr id字符串
  * @param separator 切分符 {@linkplain com.buoumall.commonService.consts.Consts}
  * @return list
  *
   */
  public static List stringToAscLongList(String str, String separator) {
    List idList = Lists.newArrayList();
    String[] idArray = str.split(separator);
    if (idArray != null) {
      for (String id : idArray) {
        idList.add(Long.valueOf(id));
      }
    }
    Collections.sort(idList);
    return idList;
  }
  
  /**
   * list根据某个属性排序
   * 
   * @param propertyName 属性名
   * @param list 需要排序的list
   * @param isAsc 是否升序(自然序)
   * @return list 排序后的list
   *
   */
  public static  List sortList(String propertyName, List list,boolean isAsc) {
    Comparator comparator = ComparatorUtils.naturalComparator();
    comparator = new BeanComparator(propertyName, comparator);
    if(!isAsc){
      comparator = ComparatorUtils.reversedComparator(comparator);
    }
    Collections.sort(list,comparator);
    return list;
  }
  
  /**
   * list根据某个属性给定的集合排序
   * 
   * @param propertyName 属性名
   * @param list 需要排序的list
   * @param from 属性对应的集合值
   * @return list 排序后的list
   *
   */
  public static  List sortList(String propertyName, List list,List from) {
    FixedOrderComparator fixedOrderComparator = new FixedOrderComparator(from);
    Comparator comparator = new BeanComparator(propertyName,fixedOrderComparator);
    Collections.sort(list,comparator);
    return list;
  }
}

你可能感兴趣的:(工具类,工具类)