记录两个最近使用到的代码片段。

1、生成有序层错

使用循环将有序集合,例如:A、B、C,生成有序层错:ABCBCACAB…。

  • 打印有序层错
private static void printOrderedStackingFaults(){
	String[] strs = {"A", "B", "C"};
	int length = strs.length;
	int size = 9;
	int j = 0;
	for(int i = 0; i < size; i++){
		int index = (i + j) % length;
		System.out.print(strs[index]);
		if((i + 1) % length == 0){
			j = getNext(j, length);
		}
	}
}
  • 获取下一轮索引
private static int getNext(int num, int length){
	return (num + 1) % length;
}
  • 运行
public static void main(String[] args) {
	printOrderedStackingFaults();
}
  • 输出
ABCBCACAB

2、Map值排序

Map中记录了某个人和其完成任务的数量,需要按照任务的数量排序:

Map<String, Integer> map = new HashMap<>();
map.put("Marie", 9);
map.put("Darcy", 5);
map.put("Anika", 3);
map.put("Olivia", 8);
map.put("Isabella", 1);
  • 排序方法
private static List<Entry<String, Integer>> sort(Map<String, Integer> map, boolean desc){
	List<Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
	Collections.sort(list, new Comparator<Entry<String, Integer>>() {
		@Override
		public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
			if(desc){
				return o2.getValue().compareTo(o1.getValue());
			}else{
				return o1.getValue().compareTo(o2.getValue());
			}
		}
	});
	return list;
}
  • 运行
List<Entry<String, Integer>> ascList = sort(map, false);
System.out.println(ascList);

List<Entry<String, Integer>> descList = sort(map, true);
System.out.println(descList);
  • 输出
[Isabella=1, Anika=3, Darcy=5, Olivia=8, Marie=9]

[Marie=9, Olivia=8, Darcy=5, Anika=3, Isabella=1]