com.jdy.ddj.common.utils.Collections3.java Source code

Java tutorial

Introduction

Here is the source code for com.jdy.ddj.common.utils.Collections3.java

Source

/**
 * Copyright (c) 2005-2012 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.jdy.ddj.common.utils;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * Collections.
 * JDKColllectionsGuavaCollections2?, ??Collections3.
 *
 * @author calvin
 */
public class Collections3 {

    private Collections3() {
    }

    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 Reflections.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 Reflections.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);
    }
}