Jeeste4專題-ListUtils工具類

常用方法:

方法名 用途
public class ListUtils extends org.apache.commons.collections.ListUtils {

	/**
     * 是否包含字符串
     * @param str 驗證字符串
     * @param strs 字符串組
     * @return 包含返回true
     */ 	
    public static boolean inString(String str, List<String> strs){
		if (str != null && strs != null){
        	for (String s : strs){
        		if (str.equals(StringUtils.trim(s))){
        			return true;
        		}
        	}
    	}
    	return false;
    }
    
	public static <E> ArrayList<E> newArrayList() {
		return new ArrayList<E>();
	}
	
	@SafeVarargs
	public static <E> ArrayList<E> newArrayList(E... elements) {
		ArrayList<E> list = new ArrayList<E>(elements.length);
		Collections.addAll(list, elements);
		return list;
	}
	
	public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
		return (elements instanceof Collection) ? new ArrayList<E>(cast(elements))
				: newArrayList(elements.iterator());
	}
	
	public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
		ArrayList<E> list = newArrayList();
		addAll(list, elements);
		return list;
	}
	
	public static <E> LinkedList<E> newLinkedList() {
		return new LinkedList<E>();
	}
	
	public static <E> LinkedList<E> newLinkedList(Iterable<? extends E> elements) {
		LinkedList<E> list = newLinkedList();
		addAll(list, elements);
		return list;
	}
	
	public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() {
		return new CopyOnWriteArrayList<E>();
	}
	
	public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList(Iterable<? extends E> elements) {
		Collection<? extends E> elementsCollection = (elements instanceof Collection)
				? cast(elements) : newArrayList(elements);
		return new CopyOnWriteArrayList<E>(elementsCollection);
	}
	
	private static <T> Collection<T> cast(Iterable<T> iterable) {
		return (Collection<T>) iterable;
	}

	private static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
		boolean wasModified = false;
		while (iterator.hasNext()) {
			wasModified |= addTo.add(iterator.next());
		}
		return wasModified;
	}

	public static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
		if (elementsToAdd instanceof Collection) {
			Collection<? extends T> c = cast(elementsToAdd);
			return addTo.addAll(c);
		}
		return addAll(addTo, elementsToAdd.iterator());
	}
	
	/**
	 * 提取集合中的對象的兩個屬性(通過Getter函數), 組合成Map.
	 * @param collection 來源集合.
	 * @param keyPropertyName 要提取爲Map中的Key值的屬性名.
	 * @param valuePropertyName 要提取爲Map中的Value值的屬性名.
	 */
	@SuppressWarnings("unchecked")
	public static Map extractToMap(final Collection collection, final String keyPropertyName,
			final String valuePropertyName) {
		Map map = new HashMap(collection.size());
		try {
			for (Object obj : collection) {
				map.put(PropertyUtils.getProperty(obj, keyPropertyName),
						PropertyUtils.getProperty(obj, valuePropertyName));
			}
		} catch (Exception e) {
			throw ReflectUtils.convertReflectionExceptionToUnchecked("", e);
		}
		return map;
	}

	/**
	 * 提取集合中的對象的一個屬性(通過Getter函數), 組合成List.
	 * @param collection 來源集合.
	 * @param propertyName 要提取的屬性名.
	 */
	@SuppressWarnings("unchecked")
	public static <T> List<T> extractToList(final Collection collection, final String propertyName) {
		if (collection == null){
			return newArrayList();
		}
		List list = new ArrayList(collection.size());
		try {
			for (Object obj : collection) {
				list.add(PropertyUtils.getProperty(obj, propertyName));
			}
		} catch (Exception e) {
			throw ReflectUtils.convertReflectionExceptionToUnchecked("", e);
		}
		return list;
	}

	/**
	 * 提取集合中的對象的一個屬性(通過Getter函數), 組合成List.
	 * @param collection 來源集合.
	 * @param propertyName 要提取的屬性名.
	 * @param prefix 符合前綴的信息(爲空則忽略前綴)
	 * @param isNotBlank 僅包含不爲空值(空字符串也排除)
	 */
	public static List<String> extractToList(final Collection collection, final String propertyName, 
			final String prefix, final boolean isNotBlank) {
		List<String> list = new ArrayList<String>(collection.size());
		try {
			for (Object obj : collection) {
				String value = (String)PropertyUtils.getProperty(obj, propertyName);
				if (StringUtils.isBlank(prefix) || StringUtils.startsWith(value, prefix)){
					if (isNotBlank){
						if (StringUtils.isNotBlank(value)){
							list.add(value);
						}
					}else{
						list.add(value);
					}					
				}				
			}
		} catch (Exception e) {
			throw ReflectUtils.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);
	}

	/**
	 * 轉換Collection所有元素(通過toString())爲String, 中間以 separator分隔。
	 */
	public static String convertToString(final Collection collection, final String separator) {
		return StringUtils.join(collection, separator);
	}

	/**
	 * 轉換Collection所有元素(通過toString())爲String, 每個元素的前面加入prefix,後面加入postfix,如<div>mymessage</div>。
	 */
	public static String convertToString(final Collection collection, final String prefix, final String postfix) {
		StringBuilder builder = new StringBuilder();
		for (Object o : collection) {
			builder.append(prefix).append(o).append(postfix);
		}
		return builder.toString();
	}

	/**
	 * 判斷是否爲空.
	 */
	public static boolean isEmpty(Collection collection) {
		return (collection == null || collection.isEmpty());
	}

	/**
	 * 判斷是否爲不爲空.
	 */
	public static boolean isNotEmpty(Collection collection) {
		return !(isEmpty(collection));
	}

	/**
	 * 取得Collection的第一個元素,如果collection爲空返回null.
	 */
	public static <T> T getFirst(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}
		return collection.iterator().next();
	}

	/**
	 * 獲取Collection的最後一個元素 ,如果collection爲空返回null.
	 */
	public static <T> T getLast(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}
		//當類型爲List時,直接取得最後一個元素 。
		if (collection instanceof List) {
			List<T> list = (List<T>) collection;
			return list.get(list.size() - 1);
		}
		//其他類型通過iterator滾動到最後一個元素.
		Iterator<T> iterator = collection.iterator();
		while (true) {
			T current = iterator.next();
			if (!iterator.hasNext()) {
				return current;
			}
		}
	}

	/**
	 * 返回a+b的新List.
	 */
	public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
		List<T> result = new ArrayList<T>(a);
		result.addAll(b);
		return result;
	}

	/**
	 * 返回a-b的新List.
	 */
	public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
		List<T> list = new ArrayList<T>(a);
		for (T element : b) {
			list.remove(element);
		}
		return list;
	}

	/**
	 * 返回a與b的交集的新List.
	 */
	public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
		List<T> list = new ArrayList<T>();
		for (T element : a) {
			if (b.contains(element)) {
				list.add(element);
			}
		}
		return list;
	}
	
//	/**
//	 * 將字符串使用“,”分隔,轉換爲,多對多中間表列表的轉換
//	 * @param clazz 當前實體類
//	 * @param attrNameOne 中間表A字段
//	 * @param attrValueOne 中間表A字段值
//	 * @param attrNameTwo 中間表B字段名
//	 * @param attrValueTwos 中間表B字段值(多個採用“,”分隔)
//	 */
//	public static <T> List<T> toManyToManyList(Class<T> clazz, String attrNameOne,
//			String attrValueOne, String attrNameTwo, String attrValueTwos){
//		List<T> list = ListUtils.newArrayList();
//		if (attrValueTwos != null){
//			for (String attrValueB : StringUtils.split(attrValueTwos, ",")){
//				try {
//					T t = clazz.newInstance();
//					ReflectUtils.invokeSetter(t, attrNameOne, attrValueOne);
//					ReflectUtils.invokeSetter(t, attrNameTwo, attrValueB);
//					list.add(t);
//				} catch (InstantiationException e) {
//					e.printStackTrace();
//				} catch (IllegalAccessException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//		return list;
//	}
	
	/**
	 * 列表分頁方法
	 * @param list 數據源
	 * @param pageSize 每頁大小
	 * @param pageCallback 分頁回調,返回當前頁的數據及分頁信息(pageList, pageNo, pageSize)
	 * @author ThinkGem
	 */
	public static <T> void pageList(List<T> list, int pageSize, MethodCallback pageCallback){
		if (list != null && list.size() > 0){

			int count = list.size(), pageNo = 1;
			int totalPage = (count + pageSize - 1) / pageSize;
			
			while(true){

				// 執行回調,分頁後的數據
				List<T> pageList = getPageList(list, pageNo, pageSize, totalPage);
				if (pageList.size() > 0){
					pageCallback.execute(pageList, pageNo, pageSize, totalPage);
				}
				
				// 如果爲最後一頁,則跳出循環
				if (pageNo >= totalPage){
					break;
				}
				
				// 頁數加一繼續下一頁
				pageNo++;
			}
		}
	}
	
	/**
	 * 列表分頁方法
	 * @param list 源數據
	 * @param pageNo 當前頁碼
	 * @param pageSize 每頁顯示條數
	 * @param totalPage 總頁碼數
	 * @author ThinkGem
	 */
	private static <T> List<T> getPageList(List<T> list, int pageNo, int pageSize, int totalPage) {
		int fromIndex = 0; // 從哪裏開始截取
		int toIndex = 0; // 截取幾個
		if (list == null || list.size() == 0){
			return new ArrayList<T>();
		}
		// 當前頁小於或等於總頁數時執行
		if (pageNo <= totalPage && pageNo != 0) {
			fromIndex = (pageNo - 1) * pageSize;
			if (pageNo == totalPage) {
				toIndex = list.size();
			} else {
				toIndex = pageNo * pageSize;
			}
		}
		return list.subList(fromIndex, toIndex);
	}
	
	/**
	 * 本地列表排序
	 * @param list 需要排序的列表
	 * @param orderBy 排序的鍵值(如:id desc)
	 * @author ThinkGem
	 */
	public static <T> List<T> listOrderBy(List<T> list, String orderBy){
		if (list != null && StringUtils.isNotBlank(orderBy)){
			final String[] ss = orderBy.trim().split(" ");
			if (ss != null){
				final String t = ss.length==2 ? ss[1] : "asc";
				Collections.sort(list, new Comparator<T>() {
					@Override
					public int compare(T o1, T o2) {
						String s1 = StringUtils.EMPTY, s2 = StringUtils.EMPTY;
						if (o1 instanceof Map){
							s1 = ObjectUtils.toString(((Map)o1).get(ss[0]));
							s2 = ObjectUtils.toString(((Map)o2).get(ss[0]));
						}else{
							s1 = ObjectUtils.toString(ReflectUtils.invokeGetter(o1, ss[0]));
							s2 = ObjectUtils.toString(ReflectUtils.invokeGetter(o2, ss[0]));
						}
						if ("asc".equalsIgnoreCase(t)){
							return s1.compareTo(s2);
						}else{
							return s2.compareTo(s1);
						}
					}
				});
			}
		}
		return list;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章