Java Cheat Sheet

Don't you hate it when you're in the middle of writing your algorithm and you have to stop to Google syntax?

So, here’s the thing. I don’t code my projects in Java, but I’m all about staying in touch with the most used and established programming language out there.

That’s why I code the LeetCode problems in Java. Trust me, I’ve been down the frustrating rabbit hole of googling again and again for the syntax of the data structures. It’s no fun. That’s why I’m hooking you up with a concise cheat sheet for your day-to-day LeetCode problem-solving. You’re welcome.

// Using the string builder for python-esque append feel

StringBuilder sb = new StringBuilder();
sb.append(1);  // append int
sb.append('#');  // append char
sb.append(',');

sb.toString();
//Queue

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

q.add(420);
q.peek(); // 420
q.remove(); // pop first element
q.size(); // 0

Queue<String> pq = new PriorityQueue<>();
pq.poll() // rest functions  have same syntax 

//Stack
Stack<Character> stack = new Stack<Character>();
stack.push("F");
stack.pop();
stack.empty();
// Initialising the mega important, GOD of Data Structure: Hash Maps!!

HashMap<String,String> map=new HashMap<String,String>();
//Obviously we want perform some actions on th hashmap too

//Lil cute code snippet
for (String key : map.keySet()) {
     if(!map.containsKey("am_i_there_yet_?"))// boolean {
            map.put("am_i_there_yet_?", "yes");
     }
}
String areYouThere = map.get("am_i_there_yet_?"); // areYouThere = yes
//hehe 

HashSet<Integer> set= new HashSet<Integer>();
set.add("oye");
if (set.contains("oye")){
   set.remove("oye")
}
// Yes it can be confusing to remember which object needs '()'
String s = "test";
int len = s.length();

ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(0)
len = arr.length; // 1
// Can be really useful in max-min  problems
double currentMin = Double.POSITIVE_INFINITY;
double currentMax = Double.NEGATIVE_INFINITY;

int intMax = Integer.MAX_VALUE;
int intMin = Integer.MIN_VALUE;

String s = "IamAStringMan";
//character at ith index in string
Character ch = s.charAt(i);

//iterate through string -> Super Sleek
for( Character ch: s.charArray()){
  //do something
}

//Convert your string to character array in order to iterate over it
char[] chars = s.toCharArray();

//Convert your character array to string 
String.valueOf(chars)

//Convert int to char
int num = 9;
char n = (char)(num+'0');

I will keep upgrading the cheat sheet as and when required. If you found it useful, share it with fellow leet-coders and like it!