HashMap中的遍歷及Java中的排序
阿新 • • 發佈:2022-05-21
HashMap中的遍歷
public class HashMapStudy { public static void main(String[] args) { //一般來說,最好初始化一下, 小於12的就不要初始化了 // 預設的就是16,因為載入因子是0.75,也就是到16*0.75=12的時候會擴容 Map<String, String> map = new HashMap<>(3); map.put("welcome","to"); map.put("java","study"); map.put("wechat","best396975802"); //遍歷方法1: 先遍歷key , 再取出value System.out.println("遍歷方法1: 先遍歷key , 再取出value"); for (String key : map.keySet()) { System.out.println("key is "+key); System.out.println("value is "+ map.get(key)); } //遍歷方法2: 直接遍歷value System.out.println("遍歷方法2: 直接遍歷value"); for (String value : map.values()) { System.out.println("value is "+value); } //遍歷方法3: 通過遍歷entry來取Key和value,推薦的方法!!! System.out.println("遍歷方法3: 通過遍歷entry來取Key和value,推薦的方法!!!"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println("key is "+entry.getKey()); System.out.println("value is "+ entry.getValue()); } //遍歷方法4: 通過forEach方法直接遍歷key和value System.out.println("遍歷方法4: 通過forEach方法直接遍歷"); map.forEach((key,value)->{ System.out.println("key is "+ key); System.out.println("value is "+ value); }); } }
Java中的排序
升序
使用 java.util.Arrays 類中的 sort() 方法對陣列進行升序分為以下兩步:
1.匯入 java.util.Arrays 包。
2.使用 Arrays.sort(陣列名) 語法對陣列進行排序,排序規則是從小到大,即升序。
public static void main(String[] args) { // 定義含有5個元素的陣列 double[] scores = new double[] { 78, 45, 85, 97, 87 }; System.out.println("排序前陣列內容如下:"); // 對scores陣列進行迴圈遍歷 for (int i = 0; i < scores.length; i++) { System.out.print(scores[i] + "\t"); } System.out.println("\n排序後的陣列內容如下:"); // 對陣列進行排序 Arrays.sort(scores); // 遍歷排序後的陣列 for (int j = 0; j < scores.length; j++) { System.out.print(scores[j] + "\t"); } }
降序
在 Java 語言中使用 sort 實現降序有兩種方法:
1)利用 Collections.reverseOrder() 方法(Collections 是一個包裝類。
public static void main(String[] args) { Integer[] a = { 9, 8, 7, 2, 3, 4, 1, 0, 6, 5 }; // 陣列型別為Integer Arrays.sort(a, Collections.reverseOrder()); for (int arr : a) { System.out.print(arr + " "); } }
2)實現 Comparator 介面的複寫 compare() 方法,程式碼如下:
public class Test {
public static void main(String[] args) {
/*
* 注意,要想改變預設的排列順序,不能使用基本型別(int,double,char)而要使用它們對應的類
*/
Integer[] a = { 9, 8, 7, 2, 3, 4, 1, 0, 6, 5 };
// 定義一個自定義類MyComparator的物件
Comparator cmp = new MyComparator();
Arrays.sort(a, cmp);
for (int arr : a) {
System.out.print(arr + " ");
}
}
}
// 實現Comparator介面
class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
/*
* 如果o1小於o2,我們就返回正值,如果o1大於o2我們就返回負值, 這樣顛倒一下,就可以實現降序排序了,反之即可自定義升序排序了
*/
return o2 - o1;
}
}