• Sort a two-dimensional array:
    Suppose intervals is a two-dimensional array int[][].
    Arrays.sort( intervals, (a,b)->Integer.compare(a[0], b[0]) );
    Note how the lambda expression is writte. Or you can write it as:
    Arrays.sort( intervals, (a,b)->{return Integer.compare(a[0], b[0]);} );
  • Convert a linkedList of array to a two-dimensional array:
    Suppose merged is a linkedlist of array.
    merged.toArray( new int[merged.size()][] );.
    Note that you must specify the array name as an argument of the function toArray() and the size of the array.
  • incompatible types: ArrayList<ArrayList> cannot be converted to List<List>
    In Java, List is an interface, and ArrayList is a concrete class that implements the List interface. The problem arises because Java's generics are invariant. This means List<ArrayList<Integer>> is not considered a subtype of List<List<Integer>>, even though ArrayList<Integer> is a subtype of List<Integer>. To fix the error, use: ArrayList<List<Integer>>();.
  • loop chars over a string:
    For example, we have a String variable str, to iterate over its chars:

    for (int i = 0; i < str.length(); i++) {
      char c = str.charAt(i); 
      System.out.print(c)
    }
    for (char c : str.toCharArray()) { 
      System.out.print(c);
    }
  • Convert values of Map to ArrayList:

    HashMap<Integer, String> map = new HashMap<>();
          map.put(1, "Apple");
          map.put(2, "Banana");
          map.put(3, "Cherry");
    
          // Convert values to ArrayList
          ArrayList<String> list = new ArrayList<>(map.values());
  • Char in Java
    The char data type in Java is used to store a single 16-bit Unicode character. It has a minimum value of \u0000 (or 0) and a maximum value of \uffff (or 65,535). In Java, if you attempt to assign a value that is outside the range of the char data type to a char variable, it will result in a compilation error. To convert a char array ca to string, simply use new String(ca).
  • Fill a two dimensional array with the same value
    In order to fill a multidimensional array, we use the for loop to fill each row of the multidimensional array. For example, if we want to fill a two dimensional array dp with -1, we could do:

    int[][] dp = new int[2001][2001];
    for(int i=0;i<dp.length;i++) Arrays.fill( dp[i], -1 );
  • remove() in ArrayList
    For datatype ArrayList, there are two commonly used overloads of the method remove() as below. remove(int index): This method removes the element at the specified position in the list. remove(Object o): This method removes the first occurrence of the specified element from the list, if it is present. If you have an ArrayList<Integer> and you call remove with an int argument, you are actually calling remove(int index). This is because Java chooses the most specific method applicable, and int is a more specific match for int index than for Object. If we want to call remove(Object o), we can call remove(Integer.valueOf(num)).
  • To generate random numbers

    • Math.random(): This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.
    • java.util.Random.nextInt(): get the next random integer value from this random number generator’s sequence.
    • java.util.Random.nextInt(int n): The nextInt(int n) is used to get a random number between 0(inclusive) and the number passed in this argument(n), exclusive. For example:

      Random ran = new Random();
      int nxt = ran.nextInt(10); 
  • Split String
    split( String regex, int limit): breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
    The limit parameter can have 3 values:

    • limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
    • limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
    • limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.

    Example:

    String str = "geekss@for@geekss";
    String[] arrOfStr = str.split("@", 2);
     
    for (String a : arrOfStr)
    System.out.println(a);

    Result:

    geekss
    for@geekss
  • Compare two strings
    s1.compareTo(s2):

    • -1 if s1<s2
    • 0 if s1==s2
    • 1 if s1>s2

    Note that:

    • ==: tests for reference equality (whether they are the same object).
    • .equals(): tests for value equality (whether they contain the same data).
    // These two have the same value
    new String("test").equals("test") // --> true 
    
    // ... but they are not the same object
    new String("test") == "test" // --> false 
    
    // ... neither are these
    new String("test") == new String("test") // --> false 
    
    // ... but these are because literals are interned by 
    // the compiler and thus refer to the same object
    "test" == "test" // --> true 
    
    // ... string literals are concatenated by the compiler
    // and the results are interned.
    "test" == "te" + "st" // --> true
  • Convert String to int
    Integer.valueOf( s ), or Integer.parseInt( s ).
  • Initialize a Queue
    Since Queue is an interface, you cannot instantiate it directly. Instead, you use one of its implementing classes. A commonly used class for implementing Queue is LinkedList, which provides FIFO (first-in, first-out) queue operations. Another class you might use for a queue is ArrayDeque, because it uses a resizable array, which can provide better performance for large numbers of elements. However, it does not support null elements.

    Queue<Integer> queue = new LinkedList<>();
    queue.offer(2);
    int firstElement = queue.poll();
  • Replace an element in a ArrayList
    set(int index, Object element), for example:

    ArrayList<String> list = new ArrayList<>();
    list.add("A");
    list.set(0, "E");
  • Get the smallest greater integer of division of two integers
    Suppose we have two integers a and b, we want to get the smallest greater integer of a/b:

    int sgi = (int)Math.ceil( (double)a/b );

    Note that we have to use two castings double and int above.

  • substring in Java

    • public String substring(int begIndex);: The substring begins with the character at the specified index and extends to the end of this string.
    • public String substring(int begIndex, int endIndex);: The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. beginIndex: the begin index, inclusive. endIndex: the end index, exclusive.
  • StringBuilder in Java

    • to append: public StringBuilder append(char a);
    • to insert at given position: insert(index, str);
    • to delete a substring: public StringBuilder delete(int start, int end);
    • to reverse the order: StringBuilder reverseStr = str.reverse();
    • to get char array: str.toCharArray();
    • to convert to a String: str.toString();

    Note that to initialize a StringBuilder class with a char, we must convert to String to use the constructor: StringBuilder sb = new StringBuilder( String.valueOf(c) );

  • Convert string to int

    • Integer.valueOf();
    • Integer.parseInt().
  • Arrays.sort an int one-dimensional array
    Note that Java's Arrays.sort method that takes a Comparator as an argument is only applicable to arrays of objects, not arrays of primitives.
    For example, the following code works:

    int[][] intervals = new int[10][10];
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));

    However, the following code DOES NOT work:

    int[] freq = new int[26];
    Arrays.sort(freq, (i1, i2) -> Integer.compare(i2, i1));

    Also note that Collections.reverseOrder() only applies to object.

  • Pair class in Java
    Definition: Pair<Key Type, Value Type> var_name = new Pair<>(key, value);
    Example: Pair p1 = new Pair(3, 4);
    Method: getKey(), It returns the key for the pair; getValue(), It returns a value for the pair..
  • Initialization of Array

    Queue<int[]> q = new LinkedList<>();
    q.add(new int[] { 1,2 });
  • In Java, everything is pass-by-value
    Read this article for detailed explanation.
    The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.
    The key to understanding this is that something like

    Dog myDog;

    is not a Dog; it's actually a pointer to a Dog. The use of the term "reference" in Java is very misleading and is what causes most of the confusion here. What they call "references" act/feel more like what we'd call "pointers" in most other languages.
    What that means, is when you have

    Dog myDog = new Dog("Rover");
    foo(myDog);

    you're essentially passing the address of the created Dog object to the foo method.
    Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.
    If the Method were defined as

    public void foo(Dog someDog) {
      someDog.setName("Max");     // AAA
      someDog = new Dog("Fifi");  // BBB
      someDog.setName("Rowlf");   // CCC
    }

    Let's look at what's happening.

    • the parameter someDog is set to the value 42
    • at line "AAA"

      • someDog is followed to the Dog it points to (the Dog object at address 42)
      • that Dog (the one at address 42) is asked to change his name to Max
    • at line "BBB"

      • a new Dog is created. Let's say he's at address 74
      • we assign the parameter someDog to 74
    • at line "CCC"

      • someDog is followed to the Dog it points to (the Dog` object at address 74)
      • that Dog (the one at address 74) is asked to change his name to Rowlf

    Now let's think about what happens outside the method:
    Did myDog change?
    Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)
    It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.

  • In Java, casting of int to char
    Given a char: char c = 'C';, to get the index: int id = c-'A'. There is no need to do the casting here, because Java will use the ASCII value to do the computation. Note that Integer.valueOf('1') and Integer.valueOf("1") will output different values: Integer.valueOf('1') returns the ASCII value which is 49, while Integer.valueOf("1") returns 1. To get a char from an int, we need to do the casting using (char): char c = (char) ('A'+1);.
  • HashMap operations
    Given a hashmap: Map<String, List<String>> map = new HashMap();, map.getOrDefault("A", new ArrayList<String>()).add(B"); will NOT create the key-value pair in the map. Instead, we need to use: map.computeIfAbsent(cur, k -> new ArrayList<String>()).add(target);. Given an arraylist List<String> l = new ArrayList<>(List.of("A","B","A"));, if there are multiple of an item, to remove all of this item, we have to use: while( tmp.remove("A") ) ;.