/*Java 兩個整數相除保留兩位小數*/
float num= (float)40.5/100;
DecimalFormat df = new DecimalFormat("0.00");//格式化小數
String s = df.format(num);//返回的是String類型
System.out.println(s);
double percent = (double)5/15;
double percent3 = (double)0/1;
NumberFormat nt = NumberFormat.getPercentInstance();//獲取格式化對象
nt.setMinimumFractionDigits(2);//設置百分數精確度2即保留兩位小數
System.out.println("百分數1:" + nt.format(percent));//最後格式化並輸出
System.out.println("百分數3:" + nt.format(percent3));
/* Java獲取時間差,分鐘差*/
SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date from=(Date) dfs.parse("2017-10-07 14:14:00");
Date to = (Date) dfs.parse("2017-10-07 14:30:00");
long minutes=(to.getTime()-from.getTime())/(1000*60);//除以1000是爲了轉換成秒 System.out.println(minutes);
控制檯輸出結果:
0.41
百分數1:33.33%
百分數3:0.00%
16
//如何根據hashMap中的value值進行排序。
package
Map;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
import
java.util.List;
import
java.util.Map;
import
java.util.Map.Entry;
import
java.util.TreeMap;
public
class
SortMap {
public
static
void
main(String[] args) {
Map map=
new
TreeMap ();
map.put(
"圖書"
,
4
);
map.put(
"音像"
,
6
);
map.put(
"素材"
,
9
);
map.put(
"音樂"
,
8
);
map.put(
"影視"
,
7
);
map.put(
"動漫"
,
4
);
map.put(
"歌曲"
,
3
);
map.put(
"圖片"
,
2
);
map.put(
"圖標"
,
6
);
ArrayList<Map.Entry<String,Integer>> entries= sortMap(map);
for
(
int
i=
0
;i<
5
;i++){
System. out.print(entries.get(i).getKey()+
":"
+entries.get(i).getValue());
}
}
public
static
ArrayList<Map.Entry<String,Integer>> sortMap(Map map){
List<Map.Entry<String, Integer>> entries =
new
ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries,
new
Comparator<Map.Entry<String, Integer>>() {
public
int
compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) {
return
obj2.getValue() - obj1.getValue();
}
});
return
(ArrayList<Entry<String, Integer>>) entries;
}
}
如何根據h裏面value的值進