Java Syntax

LiveRunGrow
4 min readSep 14, 2020

--

I notice that i frequently stumble on Java syntax during interviews or normal coding practices and end up having to google. This is bad and reflects how “unfamiliar” i am with the syntax even though i do code in Java the most often out of all the languages that i know. Oops.

This post serves to rectify my forgetfulness and i want to list down all the common syn-taxes that i should remember.

First and foremost, we need to do the correct import.

import java.util.*;

We have to take in inputs for the program as well. However, during interviews, it is best to not take in inputs in the form of scanner. One way to do so is to initialise a variable input and use that instead.

Hence, i also need to be familiar with the initialisation below.

int[] array = new int[]{1,2,3,4};

int[] array = new int[5];

String[] word = new String[]{"Hi", "Bye", "Hola"};

List<Map<String, Integer>> list = List.of(
Map.of(“a”, 1, “b”, 11, “c”, 0, “d”, 0),
Map.of(“a”, 1, “b”, 5, “c”, 0, “d”, 0),
Map.of(“a”, 1, “c”, 0, “d”, 0),
Map.of(“a”, 1, “b”, 2, “c”, 0, “d”, 0)
);

Map<Integer, List<Integer>> graph = new HashMap<>() {

{

put(0, Arrays.asList(1));

put(1, Arrays.asList(0, 2, 3));

put(2, Arrays.asList(1, 3));

put(3, Arrays.asList(1, 2));

}

}

int[][] arr = new int[row][col];

boolean [][] dp = new boolean[][];

int[][] parentChildPairs1 = new int[][] {

{1, 3}, {2, 3}, {3, 6}, {5, 6}, {5, 7}, {4, 5},

{4, 8}, {4, 9}, {9, 11}, {14, 4}, {13, 12}, {12, 9},

{15, 13}

};

returning an empty int[] return new int[0]

Converting an arraylist to int[] arraylistName.stream().mapToInt(i->i).toArray()

Pair

Pair<String, Integer> node = …..;
String word = node.getKey();
int level = node.getValue();

Comparators

Next, Comparators are quite commonly used.

PriorityQueue<Node> pq = new PriorityQueue<Node>(new NodeComparator()); // Initialise comparatorstatic class NodeComparator implements Comparator<Node>{
public int compare(Node n1, Node n2){
if(n1.getNum()<n2.getNum()) return 1;
else return -1;
}
// A shorter way of initialising priority queuePriorityQueue<Integer> pq = new PriorityQueue<Integer>((Integer n1, Integer n2) -> { return n1.compareTo(n2);});// The intention of the comparator below is to output an array with descending order according to their number position.static class NumberComparator implements Comparator<Integer>{
public int compare(Integer val1, Integer val2){
String first = String.valueOf(val1)+String.valueOf(val2);
String second = String.valueOf(val2)+String.valueOf(val1);
if(Integer.parseInt(first)>Integer.parseInt(second)){
return -1;
}
return 1;
}
}
public class Player implements Comparable<Player>{ public int compareTo(Player other){ return (this.getRanking() - otherPlayer.getRanking());
}
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x,y) -> Integer.compare(y,x));

Note that we only can use Wrapper types. We cannot use primitive types such as int, char. We have to use Integer, Character etc..

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects. Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects).

Note that we cannot do Arrays.sort for Collections objects such as List. So we remember there is Collections.sort();

Collections.sort(pairs, Comparator.comparing(Employee::getKey).thenComparing(Employee::getValue));

Check if a character is an alphabet

public static boolean isAlphabet(character ch){

return (ch>='a' && ch<='z')|| (ch>='A' && ch<='z');

}

Creating a HashSet with a single item

  • new HashSet<>(Collections.singletonList(“this is a string”))

Creating LinkedList with a single item

  • LinkedList<String> l = new LinkedList<String>(Arrays.asList(s.substring(s.length()-1)));

Creating Array of ArrayList

  • ArrayList<Integer> [] graph = new ArrayList[10];

PQ, Q and HS methods names are almost the same… only stack differs from them.

Slow and fast pointer

public ListNode mid(ListNode head){

ListNode fast = head;

ListNode slow = head; // the one pointing to the mid

while(fast!=null && fast.next!=null){

slow = slow.next;

fast = fast.next.next;

}

return slow;

}

Data Structures

PriorityQueue -> Add, Poll, Size, isEmpty

PriorityQueue<Integer> pq = new PriorityQueue<>();

add(e); peek(); poll(); contains(e); remove(e); size(); isEmpty();

Queue

Queue<Integer> q = new LinkedList<>();

add(e); peek(); poll(); size(); isEmpty(); contains();

HashSet

add(); contains(); isEmpty(); remove(e); size();

Stack -> Push, Pop, empty

Stack<Integer> s = new Stack<>();

push(e); pop(); peek(); empty(); contains(e);

String

s.charAt(index) // returns a char s.contains(Char Sequence s); s.indexOf(String s); s.length(); s.valueOf(item); // converts to String s.substring(int begin, int end); s.toCharArray(); s.toLowerCase(); s.toUpperCase(); s.equals(anotherStr);

** Note that “abc” == “abc” will evaluate to false. Need to use “abc”.equals(“abc”)

char[] ca = eachString.toCharArray(); //Convert to array of characters
Arrays.sort(ca) //Sort it;
String key = String.valueOf(ca); //Convert back to string format

myString.matches("[A-Za-z0-9]+") // Check if string is alnum
str.matches("^[a-zA-Z]*$") // Check if a string is alphabet
inputString.matches(“[0–9]+”) // checks if string is a number

Character

Character.isDigit(ch); Character.isLowerCase(ch); Character.isUpperCase(ch); Character.toString(); Character.toUpperCase(); Character.toLowerCase(); Character.isLetter(ch);

s.charAt(i)

Array

Arrays.asList(num1, num2,,); Arrays.fill(dp, amt+1); Arrays.sort(arr, new NodeComparator()); arr.length; Arrays.copyOfRange(arr, 0, k);

Integer.parseInt(item)

HashMap

HashMap<Integer, Integer> map = new HashMap<>(); map.containsKey(Object key); map.containsValue(Object value); map.entrySet(); map.values(); map.keyset(); map.get(); map.getOrDefault(); map.isEmpty(); map.put(Key, Value); map.remove(); map.size();

for (Map.Entry<Integer, Integer> each: map.entrySet()){ System.out.println(each.getValue()); System.out.println(e.getKey()); }

--

--

LiveRunGrow
LiveRunGrow

Written by LiveRunGrow

𓆉︎ 𝙳𝚛𝚎𝚊𝚖𝚎𝚛 🪴𝙲𝚛𝚎𝚊𝚝𝚘𝚛 👩‍💻𝚂𝚘𝚏𝚝𝚠𝚊𝚛𝚎 𝚎𝚗𝚐𝚒𝚗𝚎𝚎𝚛 ☻ I write & reflect weekly about software engineering, my life and books. Ŧ๏ɭɭ๏ฬ ๓є!

No responses yet