---
title: "Map 排序写法"
author: "foohsinglong"
date: "2011-08-31T10:20:49Z"
tags: ["map"]
categories: ["Web前端"]
slug: "map"
draft: false
lastmod: "2011-12-13T03:10:46Z"
id: 1162119
url: "https://foohsinglong.iteye.com/blog/1162119"
---

\[b]话不多说,直接贴代码:\[/b] \[code="java"] //对任务单的分段计划根据里程进行排序设置顺序 public void deliverySeq(Shipment shipment) { Set legs = shipment.getLegs(); Map&gt; legMaps = new HashMap&gt;(); String consignorCode = GlobalParamUtils .getGloableStringValue("CONSIGNOR\_CODE"); for (Leg leg : legs) { List legList = legMaps.get(leg.getLocationHashCode()); if (legList == null) { legList = new ArrayList(); legMaps.put(leg.getLocationHashCode(), legList); } legList.add(leg); } // 对相同的出发地,目的地的LEG进行里程归纳 Map seqMap = new HashMap(); for (Map.Entry&gt; me : legMaps.entrySet()) { Leg leg = me.getValue().get(0); Integer distance = this.getLegDistance(leg, consignorCode); seqMap.put(me.getKey(), distance); } // 调用排序 Map.Entry\[] seqMaps = this .getSortedHashtableByValue(seqMap); for (int i = 0; i &lt; seqMaps.length; i++) { List legList = legMaps.get(seqMaps\[i].getKey()); for (Leg leg : legList) { leg.setDeliverySeq(i + 1); commonDao.store(leg); } } }\[/code] \[code="java"] //Map的Integer值排序的写法 public Map.Entry\[] getSortedHashtableByValue( Map map) { Set set = map.entrySet(); Map.Entry\[] entries = (Map.Entry\[]) set.toArray(new Map.Entry\[set .size()]); Arrays.sort(entries, new Comparator() { public int compare(Object arg0, Object arg1) { Long key1 = Long.valueOf(((Map.Entry) arg0) .getValue().toString()); Long key2 = Long.valueOf(((Map.Entry) arg1) .getValue().toString()); return key1.compareTo(key2); } }); return entries; }\[/code]