Java将参与签名的字段的值放入map集合,且将字段值(value)进行升序排列,进行字典排序

  • Post author:
  • Post category:java


import java.text.ParseException;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.Set;

import java.util.TreeMap;

import java.util.concurrent.SynchronousQueue;

import org.apache.commons.beanutils.PropertyUtils;

import com.google.gson.Gson;

public class Test05 {


public static void main(String[] args) {

	Map<String, Object> p = new HashMap<String, Object>();
	System.out.println("例如---------");
	p.put("c", "123");
	p.put("t", "234");
	p.put("y", 1);
	p.put("yu", "yi");
	p.put("i", "345");
	p.put("p", "1234");
	p.put("m", 0);
	p.put("p", "1234");
	p.put("o", 3);

	HashMap<String, Object> hashMap = new HashMap<>();
	Set<String> keySet = p.keySet();
	for (String string : keySet) {
		if (p.get(string) != null && !"".equals(p.get(string))) {
			hashMap.put(string, p.get(string));
		}
	}
	p = sortByValueAscending(hashMap);
	System.out.println(new Gson().toJson(p));

}

public static <K, V extends Comparable<? super V>> Map<String, Object> sortByValueAscending(
		Map<String, Object> map) {
	System.out.println(map.entrySet());
	// Iterator<Entry<String, Object>> iterator = map.entrySet().iterator();

	List<Map.Entry<String, Object>> list = new LinkedList<Map.Entry<String, Object>>(map.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<String, Object>>() {
		@Override
		public int compare(Map.Entry<String, Object> o1, Map.Entry<String, Object> o2) {
			int compare = ((java.lang.String.valueOf(o1.getValue())))
					.compareTo((java.lang.String.valueOf(o2.getValue())));
			// System.out.println(compare);
			return compare;
		}
	});

	Map<String, Object> result = new LinkedHashMap<String, Object>();
	for (Map.Entry<String, Object> entry : list) {
		result.put(entry.getKey(), entry.getValue());
	}
	return result;
}

}



版权声明:本文为weixin_42960380原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。