Java tutorial
/** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.njmd.framework.utils; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringUtils; /** * Collections. JDKColllectionsGuavaCollections2?, ??Collections3. * * @author calvin */ public class CollectionsUtil { private CollectionsUtil() { } public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) { ArrayList<T> list = new ArrayList<T>(a); for (Iterator it = b.iterator(); it.hasNext();) { list.remove(it.next()); } return list; } /** * ????(Getter), ??Map. * * @param collection * ???. * @param keyPropertyName * ????MapKey??. * @param valuePropertyName * ????MapValue??. */ public static Map extractToMap(final Collection collection, final String keyPropertyName, final String valuePropertyName) { Map map = new HashMap(); try { for (Object obj : collection) { map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName)); } } catch (Exception e) { throw ReflectionUtil.convertReflectionExceptionToUnchecked(e); } return map; } /** * ????(Getter), ??List. * * @param collection * ???. * @param propertyName * ??????. */ public static List extractToList(final Collection collection, final String propertyName) { List list = new ArrayList(); try { for (Object obj : collection) { list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (Exception e) { throw ReflectionUtil.convertReflectionExceptionToUnchecked(e); } return list; } /** * ????(Getter), ??. * * @param collection * ???. * @param propertyName * ??????. * @param separator * . */ public static String extractToString(final Collection collection, final String propertyName, final String separator) { List list = extractToList(collection, propertyName); return StringUtils.join(list, separator); } }