作者:Andou1983 | 来源:互联网 | 2023-09-16 15:32
1.listToMap将list集合转换成map集合
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方法返回一个Objectif (o != null) {map.put((K) o, val);}} catch (IllegalAccessException | IllegalArgumentException| InvocationTargetException | IntrospectionException e) {e.printStackTrace();}}}return map;}
2.listToMapList将list集合转换成Map>
// listToMap,1个key对应的是1个元素// listToMapList,1个key对应的是1个list。list中属性id一样的,放到1个小的list中。// 可以去掉k,v这2个参数public static Map> listToMapList(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方法返回一个Objectif (o != null) {List valueList = map.get((K) o);if (valueList == null) {valueList = Lists.newArrayList();}valueList.add(val);map.put((K) o, valueList);}} catch (IllegalAccessException | IllegalArgumentException| InvocationTargetException | IntrospectionException e) {e.printStackTrace();}}}return map;}
3.beanToMap将一个JavaBean转换成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;}
4.map批量过滤key的值
public static Map MapFilter(Map map,final List keys) {return Maps.filterKeys(map, new Predicate() {@Overridepublic boolean apply(String input) {return keys.contains(input) ? false : true;}});}
5.提取集合中的对象的一个属性, 组合成List
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;}
6.将一个字符串按指定规则分割然后类型转换,放入list中
public static List stringToLongList(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));}}return idList;}