import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; public class TestSort { public static void main(String[] args) { /* sort array */ String[] array1 = new String[] { "Pineapple", "Apple", "Orange", "Banana" }; Arrays.sort(array1); for (String value : array1) { System.out.printf("%s, ", value); } System.out.println("\n"); /* reverse sort array */ String[] array2 = new String[] { "Pineapple", "Apple", "Orange", "Banana" }; Arrays.sort(array2, Collections.reverseOrder()); for (String value : array2) { System.out.printf("%s, ", value); } System.out.println("\n"); /* sort list */ List<String> list1 = Arrays.asList( "Pineapple","Apple", "Orange", "Banana" ); Collections.sort(list1); for (String value : list1) { System.out.printf("%s, ", value); } System.out.println("\n"); /* reverse sort list */ List<String> list2 = Arrays.asList( "Pineapple","Apple", "Orange", "Banana" ); Collections.sort(list2, Collections.reverseOrder()); for (String value : list2) { System.out.printf("%s, ", value); } System.out.println("\n"); /* sort set */ Set<String> set = new HashSet<>(); set.add("Pineapple"); set.add("Apple"); set.add("Orange"); set.add("Banana"); Set<String> treeSet1 = new TreeSet<>(set); for (String value : treeSet1) { System.out.printf("%s, ", value); } System.out.println("\n"); /* reverse sort set */ Set<String> treeSet2 = new TreeSet<>(Collections.reverseOrder()); treeSet2.addAll(set); for (String value : list2) { System.out.printf("%s, ", value); } System.out.println("\n"); /* sort map */ Map<String, String> map = new HashMap<>(); map.put("Pineapple","z"); map.put("Apple", "g"); map.put("Orange", "a"); map.put("Banana", "f"); Map<String, String> treeMap1 = new TreeMap<>(map); for (Map.Entry<String, String> entry : treeMap1.entrySet()) { System.out.printf( "Key : %s Value : %s \n", entry.getKey(), entry.getValue() ); } System.out.println(); /* reverse sort map */ Map<String, String> treeMap2 = new TreeMap<>(Collections.reverseOrder()); treeMap2.putAll(map); for (Map.Entry<String, String> entry : treeMap2.entrySet()) { System.out.printf("Key : %s Value : %s \n", entry.getKey(), entry.getValue() ); } System.out.println(); } }
2015-02-26 09:47
[Java] array, List, Set, Map 排序
分類:
Java
相關文章 :
訂閱:
張貼留言 (Atom)
0 回應:
張貼留言