cn.fql.utility.CollectionUtility.java Source code

Java tutorial

Introduction

Here is the source code for cn.fql.utility.CollectionUtility.java

Source

/*
 * File: $RCSfile$
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */
package cn.fql.utility;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.ListOrderedMap;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Set;
import java.util.Collection;
import java.util.Properties;
import java.util.TreeSet;
import java.io.UnsupportedEncodingException;

/**
 * The class <code>cn.fql.utility.CollectionUtility</code>
 *
 * @author User, WN ASP SSD
 * @version $Revision$
 */
public class CollectionUtility {
    /**
     * Private constructor
     */
    private CollectionUtility() {
    }

    /**
     * Merge the list of data to main list by list of key
     *
     * @param lstMain Main list
     * @param lstData List of data. Every item is also a list.
     * @param lstKey  List of key
     */
    public static void mergeData(List lstMain, List lstData, List lstKey) {
        if (lstMain == null || lstData == null || lstData.size() == 0 || lstKey == null || lstKey.size() == 0) {
            return;
        }
        for (int index1 = 0, n = lstMain.size(); index1 < n; index1++) {
            Map mapMain = (Map) lstMain.get(index1);
            Map keyValue = new HashMap();
            for (int index2 = 0, m = lstKey.size(); index2 < m; index2++) {
                Object key = lstKey.get(index2);
                keyValue.put(key, mapMain.get(key));
            }
            for (int index2 = 0, m = lstData.size(); index2 < m; index2++) {
                List lstChild = (List) lstData.get(index2);
                for (int index3 = 0, s = lstChild.size(); index3 < s; index3++) {
                    Map mapChild = (Map) lstChild.get(index3);
                    boolean flag = true;
                    for (int index4 = 0, t = lstKey.size(); index4 < t; index4++) {
                        Object key = lstKey.get(index4);
                        Object valueFromMain = keyValue.get(key);
                        Object valueFromChild = mapChild.get(key);
                        if ((valueFromMain != null && !valueFromMain.equals(valueFromChild))
                                || (valueFromMain == null && valueFromChild != null)) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        mapMain.putAll(mapChild);
                        break;
                    }
                }
            }
        }
    }

    /**
     * check each element of first list, and compare it to each element of second list.
     * element of list is <code>java.util.Map</code>, get value from map by specified key, if value
     * of element of first list are equals second's, invoke <code>java.util.Map#putAll</code>
     * of element of first list
     *
     * @param first  first collection
     * @param second second collection
     * @param key    specified key
     * @return first list
     */
    public static List joinRecords(List first, List second, String key) {
        if (first != null && second != null) {
            for (int i = 0; i < first.size(); i++) {
                Map record1 = (Map) first.get(i);
                for (Iterator iterator1 = second.iterator(); iterator1.hasNext();) {
                    Map record2 = (Map) iterator1.next();
                    if (record2.get(key) != null && record2.get(key).equals(record1.get(key))) {
                        record1.putAll(record2);
                        break;
                    }
                }
                first.set(i, record1);
            }
        }
        return first;
    }

    /**
     * Copy specified list to a new list
     *
     * @param src source list
     * @return new list
     */
    public static List copyList(List src) {
        List lstResult = new ArrayList();
        if (src != null) {
            for (Iterator it = src.iterator(); it.hasNext();) {
                lstResult.add(it.next());
            }
        }
        return lstResult;
    }

    /**
     * Convert array to a new list
     *
     * @param src source array
     * @return new list
     */
    public static List convert2List(Object[] src) {
        List lstResult = new ArrayList();
        CollectionUtils.addAll(lstResult, src);
        return lstResult;
    }

    /**
     * sepator source into two string with specified sepator , and put them into
     * to a map with first string as key, and second as value
     *
     * @param map     result map
     * @param source  source string
     * @param sepator separtor string
     */
    public static void fillMapWithStr(Map map, String source, String sepator) {
        String[] pair = StringUtility.splitStringToArray(source, sepator);
        if (pair.length == 2) {
            try {
                String key = pair[0];
                String value = pair[1];
                map.put(key, value);
            } catch (Exception e) {
                System.out.println("Pair found error");
            }
        }
    }

    /**
     * Safety add one element into collection, if collection contains specified object, it doesn't add it
     *
     * @param collection specified collection
     * @param object     specified object
     * @return @see java.util.List#add
     */
    public static boolean safeAdd(List collection, Object object) {
        return !collection.contains(object) && collection.add(object);
    }

    /**
     * Check whether map contains value
     *
     * @param map specified map
     * @return boolean value
     */
    public static boolean isEmpty(Map map) {
        boolean isEmpty = true;
        if (map != null) {
            Set keySet = map.keySet();
            Iterator it = keySet.iterator();
            while (it.hasNext()) {
                if (map.get(it.next()) != null) {
                    isEmpty = false;
                    break;
                }
            }
        }
        return isEmpty;
    }

    /**
     * return collection size
     *
     * @param collection <code>java.util.Collection</code>
     * @return size of collection
     */
    public static int getCollectionSize(Collection collection) {
        return collection != null ? collection.size() : 0;
    }

    /**
     * Return first value from list
     *
     * @param lstValue specified list
     * @return first element of specified collection, if element is null, return null
     */
    public static Object getFirstValueFromList(List lstValue) {
        if (!CollectionUtils.isEmpty(lstValue)) {
            return lstValue.get(0);
        }
        return null;
    }

    /**
     * Safety add element included in source collection to target collection
     * if target has already had element that is included in source collection,
     * it doesn't add element to target
     *
     * @param src    source collection
     * @param target target collection
     */
    public static void safetyMergeCollection(List src, List target) {
        for (Iterator it = src.iterator(); it.hasNext();) {
            Object data = it.next();
            if (!target.contains(data)) {
                target.add(data);
            }
        }
    }

    /**
     * Safety delete element included in source collection from target collection
     *
     * @param src    source collection
     * @param target target collection
     */
    public static void safetyDeleteCollection(List src, List target) {
        int srcSize = src.size();
        for (int i = 0; i < srcSize; i++) {
            Object data2Deleted = src.get(i);
            if (target.contains(data2Deleted)) {
                target.remove(data2Deleted);
                srcSize--;
            }
        }
    }

    /**
     * Sort collection with order, each group is a arraylist
     *
     * @param source source list
     * @param key    specified key which is used to be compared
     * @return <code>MapListAdapter</code>
     */
    public static ListOrderedMap sortCollectionWithOrder(List source, Object key) {
        ListOrderedMap lstOrderedMap = new ListOrderedMap();
        for (Iterator it = source.iterator(); it.hasNext();) {
            Map rowMap = (Map) it.next();
            Object keyValue = rowMap.get(key);
            List groupList = (List) lstOrderedMap.get(keyValue);
            if (groupList == null) {
                groupList = new ArrayList();
                lstOrderedMap.put(keyValue, groupList);
            }
            groupList.add(rowMap);
        }
        return lstOrderedMap;
    }

    /**
     * Return serializable data, the format of these data is placed like the following format
     * ${key}=${value}
     *
     * @param properties Properties instance
     * @return serializable data
     * @throws java.io.UnsupportedEncodingException
     *          if errors occure during text converted to UTF-8 encoding
     */
    public static byte[] getSerializablePropertiesData(Properties properties) throws UnsupportedEncodingException {
        Set keySet = properties.keySet();
        TreeSet keys = new TreeSet(keySet);
        Iterator it = keys.iterator();
        StringBuffer bf = new StringBuffer();
        while (it.hasNext()) {
            String item = (String) it.next();
            String resourceValue = (String) properties.get(item);
            bf.append(item);
            bf.append("=");
            bf.append(resourceValue);
            bf.append("\n");
        }
        return bf.toString().getBytes("UTF-8");
    }

    /**
     * Clear array object, Set each element with null value
     *
     * @param array Array instance
     */
    public static void clearArray(Object[] array) {
        for (int i = 0; i < array.length; i++) {
            array[i] = null;
        }
    }

}
/**
 * History:
 *
 * $Log$
 */