Skip to content

Latest commit

History

History
481 lines (433 loc) · 13.5 KB

File metadata and controls

481 lines (433 loc) · 13.5 KB

Java Coding

Overview

This page is to document some coding standard operations.

Basic Types

String

  • Traverse
    • substring()
      for (inti = 0; i < str.length(); i++) {
      str.substring(i, i+1);
      }
    • charAt()
      for (inti = 0; i < str.length(); i++) {
      str.charAt(i);
      }
  • Delete
    • General strategies
      • StringBuilder is more convenient to do deleting operation.
    • Delete by char
      intindex = sb.lastIndexOf("x"); // delete the last occurrence of charsb.deleteCharAt(index);
      intindex = sb.indexOf("x"); // delete the first occurrence of charsb.deleteCharAt(index);
  • Get prefix
    • If you use substring to get prefix, make sure the criteria is i <= str.length() and the initialization is int i = 1.
    for (inti = 1; i <= str.length(); i++) {
    Stringprefix = str.substring(0, i);
    }

Character

  • Check a character is a letter or number
    Character.isDigit(string.charAt(index));
    Character.isLetter(string.charAt(index));
    Character.isAlphabetic(string.charAt(index));

    NOTE: Letter doesn't contain '+' and '-'

    Character.isLetter('+'); // return falseCharacter.isLetter('-'); // return false

Integer

  • MAX value and MIN value The int type in Java can be used to represent any whole number from -2147483648 to 2147483647 (NOT symmetric).
    Integer.MAX_VALUE = 2147483647Integer.MIN_VALUE = -2147483648

Data Structures

Array

  • 1-D array
    • Initialization
      int[] array1 = newint[10];
      int[] array2 = newint[] {10,20,30,40,50,60}; // Intialize 1-D array with values
  • 2-D array
    • Initialization
      int[][] array1 = newint[10][9];
      int[][] array2 = newint[10][]; // OKint[][] array3 = {{1, 2, 3}, {4, 5, 6}}; // Intialize 1-D array with values
    • Traversal
      int[][] array = newint[3][3]; for (inti = 0; i < array.length; i++) { for (intj = 0; j < array[i].length; j++) { array[i][j] = i + j; } }
    • Assign by row
      int[][] array = newint[3][3];
      for (inti = 0; i < array.length; i++) { for (intj = 0; j < array[i].length; j++) { array[i] = newint[] {10,20,30,40,50,60};
      } }
  • Arrays
    List<Integer> list = Arrays.asList(1,2,3,4); // Initialize a list from array

List

  • Initialization
    • Initialize a list from array
      Integer[] array = {1, 2, 3, 4, 5};
      List<Integer> list = Arrays.asList(array);
    • Initialize a list of lists
      List<List<Integer>> list = newArrayList<>();
    • Initialize a linked list
      LinkedList<String> linkedList = newLinkedList<>();
  • Sorting
    • Sort a list in ascending order
      Collections.sort(list);

      NOTE: This function will not return a sorted list. It will sort the list in-place.

    • Sort a list in descending order
      Collections.sort(list);
      Collections.reverse(list);
  • Copying
    • Deep copy a list
      List<Integer> list2 = newArrayList<>(list1);
  • Common functions for list
    FunctionDescription
    sublist(i,j)Get the sub-list [i,j-1] of the existing list.
    disjoint(list1, list2)Return true if there is no common elements in both lists.

Map

  • Initialize a map with keys and values
    Map<String, String> map = newHashMap<String, String>() {
    {
    put("2", "abc");
    put("3", "def");
    put("4", "ghi");
    put("5", "jkl");
    }
    };
  • Traverse
    • Solution 1:
      for(Map.Entry<String, String> entry : map.entrySet()) {
      System.out.println(entry.getKey() + " " + entry.getValue());
      }
    • Solution 2:
      for(Stringkey : map.keySet()) {
      System.out.println(key + " " + map.get(key));
      }
  • Build 1:n relationship
    Map<Integer, List<Integer>> map = newHashMap<>();
    for (inti = 0; i < edges.length; i++) {
    /* get key and value */map.putIfAbsent(key, newArrayList<>());
    map.get(key).add(value);
    }
  • Convert all the values into a list
    Map<Integer, String> map = newHashMap<>();
    List<String> list = newArrayList<>(map.values());
  • Common functions for stack
    FunctionDescription
    getGet the value by key.
    getOrDefault(key, defaultValue)Get the value by key. If key is not in the map, return the default the value.
    putAdd or update the key-value pair into map.
    putIfAbsent(key, value)Only add the value if the key doesn't exist in the map.
    keySetGet all the keys.
    valuesGet all the values.

Stack

  • Initialize a stack

    Stack<Integer> stack = newStack<>();
  • Common functions for stack

    FunctionDescription
    pushPush an element on the top of the stack.
    popRemove and return the top element of the stack. An EmptyStackException exception is thrown if we call pop() when the invoking stack is empty.
    peekReturn the element on the top of the stack, but does not remove it.
    emptyReturn true if nothing is on the top of the stack. Else, returns false.
    searchIt determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.
  • Use pop() with caution

    • Before you call pop(), you need to check the stack is empty or not.

Queue

  • Initialize a queue

    Queue<Integer> queue = newLinkedList<>();
  • Common functions for queue

    FunctionsDescription
    addAdd element at the tail of queue.
    isEmptyCheck the queue is empty or not.
    peekReturn (but NOT remove) the element at the head element of queue. Return null if the queue is empty.
    removeRemove and returns the head element of the queue. An NoSuchElementException exception is thrown if we call remove() when the invoking queue is empty.
    pollRemove and returns the head element of the queue. Return null if the queue is empty.
  • No empty() function for queue

    • Use peek() to check the queue is empty or not.

PriorityQueue

  • Concept

    • Sorted on ascending order automatically.

      Untitled (6)

  • Initialize a priority queue

    Queue<Integer> queue = newPriorityQueue<>();
  • Initialize a max priority queue

    Queue<Integer> queue = newPriorityQueue<>(10, Collections.reverseOrder());
  • Initialize a priority queue with custom sorting

    PriorityQueue<ListNode> pq = new PriorityQueue<>(lists.length, (a, b)->(a.val - b.val));
    
  • Common functions for priority queue

    FunctionsDescription
    addAdd one element.
    containsReturns true if this queue contains the specified element.
    isEmptyCheck the queue is empty or not.
    peekReturn (but NOT remove) the head (smallest) element. Return null if the queue is empty.
    pollRemoves and returns the head (smallest) element. Return null if the queue is empty.
  • No empty() function for priority queue

    • Use peek() to check the priority queue is empty or not.

Set

  • Initialize a set
    Set<String> set = newHashSet<>();
  • Common functions for priority queue
    FunctionsDescription
    addAdd one element.
    containsCheck the element is existing in the set or not.

TreeMap

  • Concept

    • Sorted by key in ascending order automatically.
  • Initialize a tree map

    TreeMap<Integer, Integer> sortedMap = newTreeMap<>();
  • Common functions for tree map

    FunctionsDescription
    putAdd one key-value pair.
    firstKeyGet the key of the first entry (smallest in key) from tree map.
    firstEntryGet the first entry (smallest in key) from tree map.
    lastKeyGet the key of the last entry (greatest in key) from tree map.
    lastEntryGet the last entry (greatest in key) from tree map.

Util

Arrays

FunctionDescription
sort(array)Sort the elements in ascending order.
sort(array, Collections.reverseOrder())Sort the elements in descending order.
copyOfRange(array, i, j)Get the sub-array [i, j-1].
fill(array, value)Fill all the elements in the array by that value.
  • Arrays.sort (String[] arr)
    Arrays.sort(arr, (a, b)->a.length() - b.length());
    Arrays.sort(arr, (a, b)->{ returna.length() - b.length(); });
  • Time complexity: O(nlogn)

Collections

FunctionDescription
sort()Sort the elements in the collection (Default is ascending order).
max()Get the maximum element in the collection.
min()Get the minimum element in the collection.
reverse()Reverse the order of the elements (Use this function to get the descending order).
  • Collections.sort (List<int[]> list)
    Collections.sort(list, (a, b) -> {
    intcmp = Integer.compare(a[0], b[0]);
    if (cmp != 0) {
    returncmp;
    }
    returnInteger.compare(a[1], b[1]);
    });

Math

FunctionDescription
max()Get the max value among 2 values.
min()Get the min value among 2 values.

Type Conversions

  • String to char array

    Stringstr = "abcdefg";
    char[] chars = str.toCharArray();
  • char array to String

    char[] chars = {'a', 'b', 'c', 'd'}
    Stringstr1 = newString(chars); // solution 1Stringstr2 = String.valueOf(chars); // solution 2Stringstr3 = String.copyValueOf(chars); // solution 3
  • int to char array

    inti = 1234;
    char[] chars = ("" + i).toCharArray();
  • char to int

    charc = '1';
    inti = Character.getNumericValue(c);
  • int to double

    inti = 1234;
    doubled1 = Double.valueOf(i); // solution 1doubled2 = newDouble(i); // solution 2
  • int to String

    inti = 1234;
    Stringstr1 = String.valueOf(i); // solution 1Stringstr2 = newInteger(i).toString(); // solution 2
  • String to int

    Stringstr = "1234";
    inti = Integer.parseInt(str);

NOTE: When converting a string to int, need to consider overflow.

inti = 0;
Stringstr = "999999999999999999999999999999999999999999";
try {
i = Integer.parseInt(str);
} catch (Exceptione) {
/* some special handling */
}
  • array to List

    int[] ints = newint[] {1, 2, 3, 4};
    List<Integer> intList = Arrays.asList(ints);
  • List to array

    Integer[] array = newInteger[list.size()];
    list.toArray(array);

Arithmetic Operations

Division

  • The same divisor in different types causes different results.
    3 / 2 = 1
    3 / 2.0 = 1.5
    3 / 4 = 0
    

Modulo (get the remainder after division)

  • Clear the difference between division and modulo.
    999 / 100 = 9
    999 / 1000 = 0
    999 % 1000 = 999
    999 % 100 = 99
    

Custom Sorting

  • Class
    publicclassStudentimplementsComparable<Student> {
    publicintscore;
    publicintcompareTo(Students) {
    returnthis.score.compareTo(s.score); // Order by ascending order of scorereturnthis.score - s.score; // Order by ascending order of scorereturn -this.score.compareTo(s.score); // Order by descending order of scorereturns.score - this.score; // Order by descending order of score
    }
    }
  • Sort
    List<Student> students;
    Collections.sort(students);
    

Random Number

  • Get a random integer between [0, max]
    Randomran = newRandom();
    intrandomInt = ran.nextInt(max + 1);
  • Get a random integer between [min, max]
    Randomran = newRandom();
    intrandomInt = min + ran.nextInt(max - min + 1);
  • Get a random double between [0,1)
    doublerandomDouble = Math.random();
  • Get a random double between [0,max)
    doublerandomDouble = max * Math.random();