无聊写Code

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"));

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值