1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry;
public class CollectionsDemo {
public static void main(String[] args) { ArrayList<Integer> myList = new ArrayList<Integer>(); HashSet<String> mySet = new HashSet<String>(); HashMap<String, Integer> myMap = new HashMap<String, Integer>();
myList.add(2); myList.add(1); myList.add(3); mySet.add("item2"); mySet.add("item1"); mySet.add("item3"); myMap.put("key1", 999); myMap.put("key2", 888); myMap.put("key3", 777); myMap.put("key4", 777); myMap.put("key5", 666); System.out.println(myList.contains(1)); System.out.println(myList.indexOf(1)); System.out.println(mySet.contains("item1")); System.out.println(myMap.containsKey("key1")); System.out.println();
myList.remove(2); for(int i = 0; i < myList.size(); ++i) { System.out.println(myList.get(i)); } myList.add(3); for(int i : myList) { System.out.println(i); } mySet.remove("item2"); Iterator<String> it = mySet.iterator(); while(it.hasNext()) { String cur = it.next(); System.out.println(cur); } mySet.add("item2"); for(String s : mySet) { System.out.println(s); }
myMap.remove("key1"); Iterator<Entry<String, Integer>> it2 = myMap.entrySet().iterator(); while(it2.hasNext()) { Entry<String, Integer> entry = it2.next(); System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue()); } myMap.put("key1", 999); for(Entry<String, Integer> entry : myMap.entrySet()) { System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue()); }
System.out.println();
Collections.sort(myList); for(int i : myList) { System.out.println(i); } ArrayList<String> mySetList = new ArrayList<String>(mySet); Collections.sort(mySetList, (s1, s2) -> s1.compareTo(s2) * -1); for(String s : mySetList) { System.out.println(s); }
List<Entry<String, Integer>> entryList = new ArrayList<Entry<String, Integer>>(myMap.entrySet()); Collections.sort(entryList, (en1, en2) -> en1.getKey().compareTo(en2.getKey()) * -1); for(Entry<String, Integer> en : entryList) { System.out.println("key: " + en.getKey() + ", value: " + en.getValue()); } Collections.sort(entryList, (en1, en2) -> { if(!en1.getValue().equals(en2.getValue())) { return en1.getValue().compareTo(en2.getValue()) * -1; } else { return en1.getKey().compareTo(en2.getKey()); } }); for(Entry<String, Integer> en : entryList) { System.out.println("key: " + en.getKey() + ", value: " + en.getValue()); } } }
|