|
| 1 | +/******************** String, char, Integer conversion ***************/ |
| 2 | +[String to int]: Integer.parseInt(s); // return int primitive |
| 3 | +[String to Integer]: Integer.valueOf(s); // return an Integer Object |
| 4 | +[int to String]: String.valueOf(int) |
| 5 | +[char[] to String]: String str = new String(chArray); |
| 6 | +[list to array]: String[] arr = list.toArray(new String[list.size()]); |
| 7 | +[array to list]: List<String> list = Arrays.asList(arr); |
| 8 | + |
| 9 | +/********************** String ***************************/ |
| 10 | +String s = “a*b*c”; |
| 11 | +s.charAt(i); |
| 12 | +s.length(); |
| 13 | +s.substring(0, 1); // [0, 1) |
| 14 | +s.substring(1); //[1, s.length) |
| 15 | +s.equals(“b”); |
| 16 | +s.compareTo(“b*c*d”); // return -1 because s comes first in lexicographical order |
| 17 | +s.trim(); // remove tailing and padding spaces |
| 18 | +s.indexOf(“a”); // return first index of substring “a” indexOf(substring) |
| 19 | +s.indexOf(‘a’, 2); // indexOf(int ch, fromIndex), indexOf(String str, fromIndex) |
| 20 | +s.lastIndexOf(‘a’); // also we can use s.lastIndexOf(String str) |
| 21 | +s.replaceAll(substr, target); // replace all substr to target in s |
| 22 | + |
| 23 | +char[] arr = s.toCharArray(); |
| 24 | +String[] arr = s.split("\\*") // when delimiter is '*' |
| 25 | +String[] arr = s.split("\\.") // when delimiter is '.' |
| 26 | +String res = String.join(String delimiter, List<String> data); // use the delimiter to concatenate the string in data. |
| 27 | +Objects.equals(Object a, Object b); // (1)if both parameters are null return true |
| 28 | + // (2)if exactly one parameter is null return false |
| 29 | + // (3)return the result of invoking the equals() method of the first parameter passing it the second parameter |
| 30 | + // This behaviour means it is "null safe". |
| 31 | + |
| 32 | +/********************** StringBuilder ***************************/ |
| 33 | +StringBuilder sb = new StringBuilder(); |
| 34 | +sb.append(“a”); |
| 35 | +sb.insert(0, “a”); // sb.insert(int offset, char c) or sb.insert(offset, str) |
| 36 | +sb.deleteCharAt(int index); |
| 37 | +sb.reverse(); |
| 38 | +sb.toString(); |
| 39 | +sb.length(); // return the number of characters in sb, similar to str.length() |
| 40 | + |
| 41 | +/********************** Array ***************************/ |
| 42 | +int[] arr = new int[10]; |
| 43 | +Arrays.sort(arr); |
| 44 | +Arrays.fill(arr, -1); // initialize all array elements with value -1 |
| 45 | +public void helper(int[] nums); |
| 46 | +helper(new int[]{1, 2}); // initialize array in method |
| 47 | + |
| 48 | +/********************** HashMap (TreeMap), HashSet (TreeSet)***********************/ |
| 49 | +HashMap<Character, Integer> map = new HashMap<Character, Integer>(); |
| 50 | +map.put('c', 1); |
| 51 | +map.get('c'); |
| 52 | +map.getOrDefault(key, defaultValue); // if key exists return value, else return default value |
| 53 | +map.remove(‘c’); // remove key and its value |
| 54 | +map.computeIfAbsent(key, mappingFunction); // if key exists return value, else create a value by mappingFunction |
| 55 | +map.computeIfAbsent(key, k -> new HashSet<>()).add(val); |
| 56 | +map.computeIfAbsent(key, k -> new ArrayList<>()).add(val); // RECOMMENDED !!! |
| 57 | +if (map.containsKey('c')) { // check if key exists |
| 58 | +} |
| 59 | +if (map.containsValue(1)) { // check if value exists |
| 60 | +} |
| 61 | +for (Character d : map.keySet()) { // traverse key set |
| 62 | +} |
| 63 | +for (Integer i : map.values()) { // traverse value set |
| 64 | +} |
| 65 | +for(Map.Entry<Character, Integer> entry : map.entrySet()){ // traverse key-value pair |
| 66 | + entry.getKey(); |
| 67 | + entry.getValue(); |
| 68 | +} |
| 69 | +map.forEach((k,v) -> System.out.println("key: "+k+" value:"+v)); // traverse key-value pair using lamda expression to print out info |
| 70 | + |
| 71 | +map.isEmpty(); |
| 72 | +map.size(); |
| 73 | +HashSet<Integer> set = new HashSet<Integer>(); |
| 74 | +set.add(10); |
| 75 | +set.remove(10); |
| 76 | +if(set.contains(10)){ |
| 77 | +} |
| 78 | +set.size(); |
| 79 | +set.isEmpty(); |
| 80 | +setA.retainAll(setB); // setA keeps the intersection of original setA and setB; |
| 81 | +setB.removeAll(setC); // Removes from this set all of its elements that are contained in the specified collection (setB - setC) |
| 82 | +setC.addAll(setD); // union two sets of setC and setD |
| 83 | +setC.containsAll(setD); // Returns true if this set contains all of the elements of specified collection |
| 84 | +Object[] arr = setA.toArray(); // Returns an array containing all of the elements in this set. |
| 85 | + |
| 86 | +TreeMap<Integer, String> map = new TreeMap<>(); // key’s ascending order (default) |
| 87 | +map.put(2, “b”); |
| 88 | +map.put(1, “a”); |
| 89 | +map.put(3, “c”); |
| 90 | +for(String str : map.values()) // traverse in “a” “b” “c” order |
| 91 | +for(Integer num : map.keySet()) // traverse in 1, 2, 3 order |
| 92 | + |
| 93 | +TreeMap<String, Integer> treeMap = new TreeMap<>(); // sorted in lexicographical order |
| 94 | +TreeMap<Integer, Integer> treeMap = new TreeMap<>(Collections.reverseOrder()); // descending order |
| 95 | + |
| 96 | +treeMap.lowerKey(k); // return the max key that < k |
| 97 | +treeMap.floorKey(k); // return the min key that >= k |
| 98 | +treeMap.higherKey(k); // return the min key that > k |
| 99 | +treeMap.ceilingKey(k); // return the max key that <= k |
| 100 | +treeMap.firstKey(); // returns the first (lowest) key currently in this map. |
| 101 | +SortedMap<K,V> portionOfTreeMap = treeMap.headMap(K toKey); // Returns a view of the portion of this map whose keys are strictly less than toKey. |
| 102 | +NavigableMap<K,V> map = treeMap.headMap(toKey, true); // Returns a view of the portion of this map whose keys are less than or equal to toKey. |
| 103 | + |
| 104 | +Set<Integer> treeSet = new TreeSet<>(); // sort in ascending order by default |
| 105 | +treeSet.lower(Integer e); // return greatest element that is < e, or null if no such element |
| 106 | +treeSet.floor(Integer e); // return greatest element that is <= e, or null if no such element |
| 107 | +treeSet.ceiling(Integer e); // return smallest element that is >= e, or null if no such element |
| 108 | +treeSet.higher(Integer e); // return smallest element that is > e, or null if no such element |
| 109 | +treeSet.first(); // return the first element in the treeset (if min set, return minimum element) |
| 110 | +treeSet.last(); // return the last element in the treeset |
| 111 | + |
| 112 | +/********************** LinkedHashMap, LinkedHashSet *************/ |
| 113 | +Map<Integer,String> map = new LinkedHashMap<>(); |
| 114 | +map.put(1, "first"); |
| 115 | +map.put(2, "second"); |
| 116 | +map.put(3, "third"); |
| 117 | +for(Map.Entry<Integer,String> entry : map.entrySet()) |
| 118 | + System.out.println(entry.getKey(), entry.getValue()); // print order: 1, 2, 3 |
| 119 | +Set<Integer> set = new LinkedHashSet<>(); |
| 120 | + |
| 121 | +/********************** List, ArrayList, LinkedList *************/ |
| 122 | +List<Integer> list = new ArrayList<>(); |
| 123 | +list.add(14); |
| 124 | +list.add(0, 10); // list.add(int index, int value); |
| 125 | +list.get(int index); |
| 126 | +list.remove(list.size() - 1); |
| 127 | +list.set(int index, int val); // replaces element at index and returns original |
| 128 | +list.indexOf(Object o); // return first index of occurrence of specified element in the list; -1 if not found |
| 129 | +list.subList(int fromIndex, int toIndex); // return a sublist within range [fromIndex, toIndex) |
| 130 | +Collections.sort(list); // ascending order by default |
| 131 | +Collections.sort(list, Collections.reverseOrder()); // descending order |
| 132 | +Collections.sort(list, new Comparator<Integer>() { |
| 133 | + @Override |
| 134 | + public int compare(Integer o1, Integer o2) { // the Integer can be any Object instead |
| 135 | + return o1 ‐ o2;// 0‐>1 |
| 136 | + // return o2‐o1; 1‐>0 |
| 137 | + } |
| 138 | +}); |
| 139 | +list.forEach(num -> system.out.println(num)); // traverse the list and print out by using lamda function |
| 140 | + |
| 141 | +/********************** Stack, Queue, PriorityQueue, Deque ***********************/ |
| 142 | +Stack<Integer> stack = new Stack<Integer>(); |
| 143 | +stack.push(10); |
| 144 | +stack.pop(); |
| 145 | +stack.peek(); |
| 146 | +stack.isEmpty(); |
| 147 | +stack.size(); |
| 148 | +Queue<Integer> q = new LinkedList<Integer>(); |
| 149 | +q.offer(10); // q.add() is also acceptable |
| 150 | +q.poll(); |
| 151 | +q.peek(); |
| 152 | +q.isEmpty(); |
| 153 | +q.size(); |
| 154 | +PriorityQueue<Integer> pq = new PriorityQueue<>(); // minimum Heap by default |
| 155 | +PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()); // change to maximum Heap |
| 156 | +pq.add(10); |
| 157 | +pq.poll(); |
| 158 | +pq.peek(); |
| 159 | +pq.isEmpty(); |
| 160 | +pq.size(); |
| 161 | +class Node implements Comparable<Node>{ |
| 162 | + int x; |
| 163 | + int y; |
| 164 | + public Node(int x, int y){ |
| 165 | + this.x = x; |
| 166 | + this.y = y; |
| 167 | + } |
| 168 | + @Override |
| 169 | + public int compareTo(Node that){ |
| 170 | + return this.x - that.x; // ascending order / minimum Heap |
| 171 | + // return that.x - this.x; // descending order / maximum Heap |
| 172 | + } |
| 173 | +} |
| 174 | +PriorityQueue<Node> pq = new PriorityQueue<>(); |
| 175 | + |
| 176 | +import java.util.Deque; |
| 177 | +Deque<Integer> dq = new LinkedList<Integer>(); // Deque is usually used to implement monotone queue |
| 178 | +dq.addFirst(); // dq.offerFirst(); |
| 179 | +dq.addLast(); // dq.offerLast(); |
| 180 | +dq.peekFirst(); // |
| 181 | +dq.peekLast(); |
| 182 | +dq.pollFirst(); // dq.removeFirst(); |
| 183 | +dq.pollLast(); // dq.removeLast(); |
| 184 | + |
| 185 | +/************************** Random method *****************************/ |
| 186 | +Random rand =new Random(); // initialize Random object |
| 187 | +int i = rand.nextInt(100); // generate random number in [0, 100) |
| 188 | +float f = rand.nextFloat(); // generate float value in [0, 1) |
| 189 | +double d = rand.nextDouble(); // generate double value in [0.0, 1.0) |
| 190 | + |
| 191 | +/************************** Math *****************************/ |
| 192 | +Math.pow(double x, double y); // return x^y |
| 193 | +Math.round(float a); // returns the closest int to the argument |
| 194 | +Math.abs(int/float/doubld val); |
| 195 | +Math.sqrt(); |
| 196 | +Math.sin(double rad); // input is rad not angle |
| 197 | +Math.PI; |
| 198 | +Math.E; |
| 199 | + |
| 200 | +/************************** Collections/Object *****************************/ |
| 201 | +Collections.nCopies(100, new Object[]{true});// return an immutable list which contains n copies of given object |
| 202 | +getClass() // Returns the runtime class of this {@code Object} |
| 203 | +Collections.singletonList() // use it to replace Arrays.asList() when there is only one element |
| 204 | +Collections.unmodifiableSet(new HashSet<>()) // returns an unmodifiable view of the specified set. Note that, changes in specified set will be reflected in unmodifieable set. |
| 205 | + // Also, any modification on unmodifiableSet is not allowed, which triggers exception. |
| 206 | +Collections.swap(List, int i, int j); // swap the ith and jth element in list |
| 207 | + |
| 208 | +/********************* std input/output file read/write ************************/ |
| 209 | +import java.io.*; |
| 210 | +import java.net.*; |
| 211 | +Scanner in = new Scanner(System.in); |
| 212 | +int n = in.nextInt(); |
| 213 | +while(in.hasNext()){ |
| 214 | + String str = in.nextLine(); |
| 215 | +} |
| 216 | + |
| 217 | +String inputfile="in.txt"; |
| 218 | +String outputfile="out.txt"; |
| 219 | +try |
| 220 | +{ |
| 221 | + BufferedReader in = new BufferedReader(new FileReader(inputfile)); |
| 222 | + line = in.readLine(); |
| 223 | + while (line!=null) |
| 224 | + { |
| 225 | + // do something with line |
| 226 | + line=in.readLine(); |
| 227 | + } |
| 228 | + in.close(); // close the file |
| 229 | +} catch (IOException e) |
| 230 | +{ |
| 231 | + e.printStackTrace(); |
| 232 | +} |
| 233 | + |
| 234 | +try{ |
| 235 | + BufferedWriter out = new BufferedWriter(new FileWriter(outputfile)); |
| 236 | + for(String str : map.keySet()){ |
| 237 | + out.write(str + " " + map.get(str)); |
| 238 | + out.newLine(); |
| 239 | + } |
| 240 | + out.close(); // close the file |
| 241 | +}catch (IOException e) |
| 242 | +{ |
| 243 | + e.printStackTrace(); |
| 244 | +} |
| 245 | + |
| 246 | +URL wordlist = new URL("http://foo.com/wordlist.txt"); |
| 247 | +BufferedReader in = new BufferedReader(new InputStreamReader(wordlist.OpenStream())); |
| 248 | +String inputLine = null; |
| 249 | +List<String> res = new ArrayList<>(); |
| 250 | +while((inputLine = in.readLine()) != null){ |
| 251 | + res.add(inputLine); |
| 252 | +} |
0 commit comments