cn.hxh.springside.mapper.CollectionMapper.java Source code

Java tutorial

Introduction

Here is the source code for cn.hxh.springside.mapper.CollectionMapper.java

Source

/**
 * Copyright (c) 2005-2011 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Fixtures.java 1593 2011-05-11 10:37:12Z calvinxiu $
 */
package cn.hxh.springside.mapper;

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;
import cn.hxh.springside.utils.ReflectionUtils;

/**
 * ???(Getter),???.
 * 
 * @author calvin
 */
public class CollectionMapper {

    /**
     * ????(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 ReflectionUtils.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 ReflectionUtils.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);
    }
}