`

无聊写Code

    博客分类:
  • java
阅读更多
package edu.qdkj.main;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.Map.Entry;

public class Main {

	/**
	 * 随机的产生 num 个随机数
	 * 
	 * @return
	 */
	public static List randomNewList(List<Integer> list, int num) {
		List<Integer> returnList = new ArrayList<Integer>();
		for (int i = 0; i < num; i++) {
			int index = (int) (Math.random() * list.size());
			returnList.add(list.get(index));
		}
		return returnList;

	}

	/**
	 * 数列累加
	 * 
	 * @param list
	 * @return
	 */
	public static int sumList(List<Integer> list) {
		int sum = 0;
		for (Integer i : list) {
			sum += i;
		}
		return sum;
	}

	/**
	 * 将 List<List> 按照 List 的sum 进行排序 取出 list ,放在 list<map>中 map 的 key 是 i
	 * value 是 abs(sum) - Wg(最好)
	 * 
	 * @param list
	 * @param staticNum
	 *        
	 *  @param  Sort 默认是升序排列,排序模式 desc 降序
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<List> sortList(List<List> list, int staticNum,
			final String sort) {
		Map<List, Integer> map = new HashMap<List, Integer>();
		for (List l : list) {
			map.put(l, Math.abs(sumList(l) - staticNum));
		}
		List<Map.Entry<List, Integer>> list2 = new ArrayList<Map.Entry<List, Integer>>(
				map.entrySet());
		Collections.sort(list2, new Comparator<Map.Entry<List, Integer>>() {
			public int compare(Entry<List, Integer> o1, Entry<List, Integer> o2) {
				if ("desc".equals(sort)) {
					return o2.getValue() - o1.getValue();//降序
				} else {
					return o1.getValue() - o2.getValue();
				}

			}
		});
		return mapToList(list2);

	}

	/**
	 * 根据 map的 key 将map 变成list
	 * 
	 * @param map
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List mapToList(List<Map.Entry<List, Integer>> list) {
		List<List> returnList = new ArrayList<List>();
		for (Map.Entry<List, Integer> l : list) {
			returnList.add(l.getKey());
		}
		return returnList;
	}

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<List> list = new ArrayList<List>();
		List<Integer> list1 = new ArrayList<Integer>();
		for (int i = 0; i < 10; i++) {
			list1.add(i);
		}
		List list2 = randomNewList(list1, 3);
		List list3 = randomNewList(list1, 3);
		List list4 = randomNewList(list1, 3);
		list.add(list2);
		list.add(list3);
		list.add(list4);
		System.out.println(list);
		System.out.print(sortList(list, 10, "desc"));

	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics