Java tutorial
/* * Copyright 2013-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.age.back.frame.auth; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.StringUtils; /** * * * @author maurice * */ @SuppressWarnings({ "rawtypes", "unchecked" }) public class CollectionUtils extends org.apache.commons.collections.CollectionUtils { /** * ????(Getter), ??Map. * * @param collection ???. * @param keyPropertyName ????MapKey??. * @param valuePropertyName ????MapValue??. */ public static Map extractToMap(Collection collection, String keyPropertyName, String valuePropertyName) { Map map = new HashMap(); try { for (Object obj : collection) { map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName)); } } catch (Exception e) { e.printStackTrace(); } return map; } /** * ????(Getter), ??List. * * @param collection ???. * @param propertyName ??????. * * @return List */ public static <T> List<T> extractToList(Collection collection, String propertyName) { return extractToList(collection, propertyName, false); } /** * ????(Getter), ??List. * * @param collection ???. * @param propertyName ??????. * @param ignoreEmptyValue ?null"" * * @return List */ public static <T> List<T> extractToList(Collection collection, String propertyName, boolean ignoreEmptyValue) { if (collection == null) { return null; } List list = new ArrayList(); try { for (Object obj : collection) { T value = (T) PropertyUtils.getProperty(obj, propertyName); if (ignoreEmptyValue && value == null || value.toString().equals("")) { continue; } list.add(PropertyUtils.getProperty(obj, propertyName)); } } catch (Exception e) { e.printStackTrace(); } return list; } /** * ????(Getter), ??. * * @param collection ???. * @param propertyName ??????. * @param separator . */ public static String extractToString(Collection collection, String propertyName, String separator) { List list = extractToList(collection, propertyName); return StringUtils.join(list, separator); } }