Java common data type and structure operations

Java common data type and structure operations.

Primitive types

 - byte     1 byte
 - short    2 bytes
 - int      4 bytes
 - long     8 bytes
 - float    4 bytes
 - double   8 bytes

 - boolean  1 bit
 - char     2 bytes

Integer

     // parse int from String with radix
     Integer.parseInt("1101", 2);

     // convert between array and arraylist for primitives with stream
     Integer[] ints = {1, 2, 3, 4};
     List<Integer> intList = new ArrayList<>(Arrays.asList(ints));
     int[] intArray = intList.stream().mapToInt(Integer::intValue).toArray();
     System.out.println(Arrays.toString(intArray));
     
     // convert integer to binary string format
     Integer.toBinaryString(5);

     // convert to Integer from string or primitive
     Integer.valueOf("100");
     Integer.valueOf(100);

Arrays

     // array literal initiazation
     String[] words = {"hello", "world"};
     int[] nums = {1, 2, 3, 4, 5};
     
     // get length
     array.length
     
     // copy array from src to dest
     // ArrayList uses it internally to do add/remove operations which involves moving elements
     System.arraycopy(srcArray, srcStart, destArray, destStart, length);
     
     // copy array to create a new array
     // ArrayList uses it internally to grow capacity
     Arrays.copyOf(srcArray, n);
     
     // fill array with default values
     Arrays.fill(array, defaultVal);
     
     // sort array - modify in place
     Arrays.sort(array);
     
     // create sub array from existing array
     Arrays.copyOfRange(original, start, endExclusive);

ArrayList

     // create ArrayList from array of Objects
     new ArrayList<T>(Arrays.asList(objArray));
     // create ArrayList from array of Primitives, int[] for example
     IntStream.of(intArray).boxed().collect(Collectors.toList());
     Arrays.stream(intArray).boxed().collect(Collectors.toList());
     Arrays.stream(intArray).mapToObj(Integer::valueOf).collect(Collectors.toList());
     
     // convert list to array
     String[] arrayOfString = listOfString.toArray(new String[0]);
     String[] arrayOfString = listOfString.toArray(String[]::new);
     
     // check membership
     arrayList.contains(o);
     
     // add new element from end, at specified index, or add all from existing collections
     arrayList.add(e);
     arrayList.add(i, e);
     arrayList.addAll(c);
     
     // replace/override element at specified index
     arrayList.set(i, e);
     
     // get element from index
     arrayList.get(i);
     
     // iterate element with forEach
     arrayList.forEach(e -> System.out::println);
     
     // find index by given element from the start or the end
     arrayList.indexOf(o);
     arrayList.lastIndexOf(o);
     
     // remove by index or by element
     arrayList.remove(i);
     arrayList.remove(o);
     
     // get size/length of ArrayList
     arrayList.size();
     
     // sub group array list
     List<Integer> persons = getListOfPersons();
     List<List<Integer>> results = new ArrayList<>();
     int groupSize = 3;
     for (int i = 0; i + groupSize <= persons.size(); i += groupSize) {
       results.add(persons.subList(i, i + groupSize));
     }

String

     // get character or character array from string
     char c = str.charAt(i);
     char[] chars = str.toCharArray();
     
     // get IntStream from string's characters
     IntStream intStream = str.chars();

     // get index of character or sub string
     str.indexOf(ch);
     str.indexOf(str);
     str.indexOf(str, fromIdx);
     str.lastIndexOf(ch);
     
     // get length/number or characters
     str.length();
     
     // test against regex to see if it matches given pattern
     str.matches(regex);
     
     // replace all - either char or substring
     str.replace(chOld, chNew);
     str.replace(subOld, subNew);
     
     // replace all with regex
     str.replaceAll(regex, replacement);
     
     // check if it contains sub string
     str.contains(s);
     
     // check if it starts with or ends with sub string
     str.startsWith(s);
     str.endsWith(s);
     
     // convert to character array
     str.toCharArray();
     
     // get string from character array
     new String(charArray);
     
     // split into array of words by pattern
     str.split(regex);
     
     // join array or iter into a string with delimiter
     String.join(d, words);
     
     // format string output: "13:02:30"
     String.format("%02d:%02d:%02d", 13, 2, 30);
     
     // get sub string by start or/and end index
     str.substring(begin);
     str.substring(begin, end);
     
     // convert to upper case or lower case versions
     str.toUpperCase();
     str.toLowerCase();
     
     // get rid of both leading and trailing white space
     str.trim();
     // get rid of leading white space
     str.replaceAll("^\\s+", "");
     // get rid of trailing white space
     str.replaceAll("\\s+$", "");
     
     // get a string from primitive, object, or char array
     String.valueOf(x);
     
     // reverse characters of a string
     new StringBuilder(str).reverse().toString();
     
     // calculate number's digits multiply or addition with string format
     // calculate "234" => 2 * 3 * 4
     Integer.toString(234).chars().reduce(1, (r, i) -> r * (i - '0'));
     // calculate "234" => 2 + 3 + 4
     Integer.toString(234).chars().reduce(0, (r, i) -> r + (i - '0'));
     Arrays
       .stream("234".split(""))
       .map(Integer::valueOf)
       .reduce((d1, d2) -> d1 + d2)
       .get();
     Arrays
       .stream("234".split(""))
       .mapToInt(Integer::valueOf)
       .sum();

HashMap

     // check if it contains key or value
     hmap.containsKey(k);
     hmap.containsValue(v);
     
     // get entry set, key set or value collection
     hmap.entrySet();
     hmap.keySet();
     hmap.values();
     
     // iterate entries with forEach
     hmap.forEach((k, v) -> {
       Sytem.out.println(k + '=' + v);
     });
     
     // get value by key, or default if not available
     hmap.get(k);
     hmap.getOrDefault(k, d);
     
     // put key-value pair into HashMap, or put all from another map
     hmap.put(k, v);
     hmap.putAll(m);
     
     // get size of entries
     hmap.size();
     
     // remove all, remove by key or key-value
     hmap.clear();
     hmap.remove(k);
     hmap.remove(k, v);

Character

     // convert to string from char array
     new String(char[] chars);
     Arrays.toString(char[] chars);
     
     // unicode mapping
     - '0' ~ '9': 48 ~ 57
     - 'A' ~ 'Z': 65 ~ 90
     - 'a' ~ 'z': 97 ~ 122
     
     // cast int <> char
     (char)65;
     (char)('A' + 1);
     (int)'A';
     
     
     // convert char to string
     String.valueOf('a');
     Character.toString('a');
     
     // check if lower case upper case
     Character.isLowerCase(ch);
     Character.isUpperCase(ch);
     
     // convert between integer 0 ~ 9 literal and char '0' ~ '9'
     char c = Character.forDigit(digit, 10);
     int d = Character.digit(ch, 10);

Math

     // get absolute value
     Math.abs(d);
     
     // get ceil, floor, round value
     Math.ceil(d);
     Math.floor(d);
     Math.round(d);
     
     // get max or min value from two
     Math.max(a, b);
     Math.min(a, b);
     
     // get power of a by b
     Math.pow(a, b);
     
     // get a random number
     Math.random();
     
     // get sqrt or cbrt
     Math.sqrt(d);
     Math.cbrt(d);
     
     // get constants
     Math.PI;
     Math.E;

HashSet

     // create set from int array
     Arrays.stream(intArray).boxed().collect(Collectors.toSet());
     
     // literal init - not recommended due to performance concern
     Set<Character> vowels = new HashSet<>() {
     {
       add('a');
       add('o');
       add('e');
       add('i');
       add('u');
     }
     };
     
     // get intersection of two sets
     setA.retainAll(setB);

Stack

     // stack basic operations
     Stack<E> stack = new Stack<>();
     stack.push(E e);
     stack.pop();
     stack.peek();
     stack.empty();

Stream

     // convert iterables and arrays to stream
     listOfObj.stream();
     Arrays.stream(someArray);
     Stream.of(T... values); // internally uses Arrays.stream()

ArrayDeque

     // ArrayDeque used as Stack (LIFO)
     Deque<String> stack = new ArrayDeque<>();
     stack.push("hello1");
     stack.push("hello2");
     stack.push("hello3");
     assert "hello3".equals(stack.peek());
     while (!stack.isEmpty()) {
       System.out.println(stack.pop());
     }

     // ArrayDeque used as Queue (FIFO)
     Deque<String> queue = new ArrayDeque<>();
     queue.add("hello1");
     queue.add("hello2");
     queue.add("hello3");
     assert "hello1".equals(queue.peek());
     while (!queue.isEmpty()) {
       System.out.println(queue.remove());
     }

TreeMap

     // Sort hash map by key in ascending (default) order
     Map<Integer, String> sortedMap = new TreeMap<>(unsortedHashMap);
     
     // Sort hash map by key in descending (custom) order
     Map<Integer, String> customSortedMap = new TreeMap<>((k1, k2) -> k2 - k1);
     customSortedMap.putAll(unsortedHashMap);

PriorityQueue

     // by default dequeues in natural order
     PriorityQueue<Integer> queue1 = new PriorityQueue<>();
     queue1.add(100);
     queue1.add(20);
     queue1.add(60);
     queue1.add(50);
     queue1.add(88);
     while (!queue1.isEmpty()) {
         System.out.println(queue1.remove());
     }
     System.out.println("#################");
     // customize the order
     PriorityQueue<Integer> queue2 = new PriorityQueue<>((e1, e2) -> e2 - e1);
     queue2.add(100);
     queue2.add(20);
     queue2.add(60);
     queue2.add(50);
     queue2.add(88);
     while (!queue2.isEmpty()) {
         System.out.println(queue2.remove());
     }

java