常用Java程式碼彙總
阿新 • • 發佈:2018-11-30
排序問題
private Map<String, Long> sortMapByValueLong(Map<String, Long> oriMap, final boolean isAsc) { Map<String, Long> sortedMap = new LinkedHashMap<String, Long>(); if (oriMap != null && !oriMap.isEmpty()) { List<Map.Entry<String, Long>> entryList = new ArrayList<Map.Entry<String, Long>>(oriMap.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<String, Long>>() { public int compare(Entry<String, Long> entry1, Entry<String, Long> entry2) { long value1 = 0, value2 = 0; try { value1 = entry1.getValue(); value2 = entry2.getValue(); } catch (NumberFormatException e) { value1 = 0; value2 = 0; } // 判定 long rst = 0; if (isAsc) { rst = value1 - value2; } else { rst = value2 - value1; } return (int)rst; } }); Iterator<Map.Entry<String, Long>> iter = entryList.iterator(); Map.Entry<String, Long> tmpEntry = null; while (iter.hasNext()) { tmpEntry = iter.next(); sortedMap.put(tmpEntry.getKey(), tmpEntry.getValue()); } } return sortedMap; }
Map轉list
Map<String,String> map=new HashMap<String,String>();
map.put("1", "1");
map.put("2", "2");
List<Map.Entry<String, String>> list=new ArrayList<Map.Entry<String,String>>(map.entrySet());
帶有小數點的字串轉為int
int abc =Double.valueOf(num).intValue();