---
# System prepended metadata

title: comparator 實作
tags: [comparator, java]

---

# comparator 實作


前言: 

java server從DB取資料, 取出的List再回傳到client端時需要依照特定資料行的順序排序 該排序非以常見column desc asd可處理,
與其寫複雜的sql卡住db不如將排序工作放到java server中處理,
1. java server 比db容易水平擴展, 要卡db不如卡server
2. sql 維護不易....

JAVA List\<T\>提供sort方法 需實作comparator interface 



```java=
package cycle11_search_tree;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class compar_test {

	public static void main(String[] args) {

		List<Map<String, Object>> raw = new LinkedList<>();

		Map<String, Object> x1 = new HashMap<>() {
			{
				put("key", "333");
			}
		};
		Map<String, Object> y1 = new HashMap<>() {
			{
				put("key", "222");
			}
		};
		Map<String, Object> z1 = new HashMap<>() {
			{
				put("key", "111");
			}
		};

		raw.add(y1);
		raw.add(x1);
		raw.add(z1);

		for (Map<String, Object> m : raw) {
			System.out.println(stringtify(m.get("key")));
		}
		System.out.println("=========以上未排序==========");

		// 依此順序進行排序
		ArrayList<String> order = new ArrayList<>() {
			{
				add("333");
				add("222");
				add("111");
			}
		};

		System.out.print("排序順序:");
		for (String s : order) {
			System.out.print(s + ",");
		}
		System.out.println();

		// 建map 方便找比較順序
		Map<String, Integer> priority = new HashMap<>();
		for (int i = 0; i < order.size(); i++) {
			priority.put(order.get(i), i);
		}

		// non stream寫法
//		Comparator<Map<String, Object>> spe = new Comparator<>() {
//			@Override
//			public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//
//				String a = stringtify(o1.get("key"));
//				Integer a_pri = priority.get(a);
//
//				String b = stringtify(o2.get("key"));
//				Integer b_pri = priority.get(b);
//
//				return a_pri - b_pri; // 小於0時交換順序
//			}
//		};

		// stream 寫法
		Comparator<Map<String, Object>> spe1 = (o1, o2) -> {

			String a = stringtify(o1.get("key"));
			Integer a_pri = priority.get(a);

			String b = stringtify(o2.get("key"));
			Integer b_pri = priority.get(b);

			return a_pri - b_pri; // 小於0時交換順序
		};

		raw.sort(spe1);

		System.out.println("=========以下已排序==========");
		for (Map<String, Object> m : raw) {
			System.out.println(stringtify(m.get("key")));

		}

//		System.out.println(stringtify(null)); // null test

	}

	static private String stringtify(Object object) {
		return Optional.ofNullable(object)
				.map(Object::toString)
				.orElse("");
	}

}


```


###### tags: `java` `comparator`
