1.listToMap将list集合转换成map集合
public static <K, V> Map<K, V> listToMap(String keyName, List<V> list) { Map<K, V> 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; }2.listToMapList将list集合转换成Map<K, List<V>>// listToMap,1个key对应的是1个元素 // listToMapList,1个key对应的是1个list。list中属性id一样的,放到1个小的list中。 // 可以去掉k,v这2个参数 public static <K, V> Map<K, List<V>> listToMapList(String keyName,List<V> list) { Map<K, List<V>> 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) { List<V> 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<String, Object> bean2Map(Object obj) { if (obj == null) { return null; } Map<String, Object> 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<String, Object> MapFilter(Map<String, Object> map, final List<String> keys) { return Maps.filterKeys(map, new Predicate<String>() { @Override public boolean apply(String input) { return keys.contains(input) ? false : true; } }); }5.提取集合中的对象的一个属性, 组合成Listpublic static <T> List<T> extractToList(final Collection<?> collection, final String propertyName) { if (CollectionUtils.isEmpty(collection)) { return null; } List<T> list = new ArrayList<T>(collection.size()); CollectionUtils.collect(collection, new BeanToPropertyValueTransformer(propertyName), list); return list; }6.将一个字符串按指定规则分割然后类型转换,放入list中public static List<Long> stringToLongList(String str,String separator){ List<Long> idList = Lists.newArrayList(); String[] idArray = str.split(separator); if(idArray != null){ for(String id:idArray){ idList.add(Long.valueOf(id)); } } return idList; }
新闻热点
疑难解答