Algo Drills
String Parsing and Conversion in Java
Strings to Primitives using parse
parseInt()
and parseDouble()
- Used for parsing a String into a primitive int or double.
int i = Integer.parseInt("12345"); int j = Integer.valueOf("1234").intValue();//From String to Wrapper to Primitive
Creating Wrapper Instances using valueOf
valueOf()
- Used to create instances of wrapper classes from a String or primitive.
Integer fromPrimitiveInt = Integer.valueOf(25); // From primitive Integer fromString = Integer.valueOf("90"); // From String
String.valueOf()
- Converts primitives and char arrays into Strings.
String intAsString = String.valueOf(42); String doubleAsString = String.valueOf(3.14159); String booleanAsString = String.valueOf(true); String charArrayAsString = String.valueOf(new char[] {'H', 'e', 'l', 'l', 'o'});
Key Differences
Between parse
and valueOf
-
parse
: Converts a String to a primitive type. -
valueOf
: Converts a String or primitive type to a Wrapper object.
Read more about parse and valueOf
Between parse
and format
-
parse
: Converts a String to the data type of the class being parsed.LocalDate startLocalDate = LocalDate.parse("2023-10-30"); // yyyy-MM-dd format by default
-
format
: Converts an object to a formatted String.String formattedDate = startLocalDate.format(DateTimeFormatter.ofPattern("dd-MMM-YYYY"));
1D Array
-
a.length
is a field in array - Declare simple array
int[] a = new int[3];//use [] for array instead of () int[] a = new int[] {1,2,3}; int[] b = {1,2,3};//Same as above
- Declare an ArrayList using
Arrays.asList()
List<String> list = Arrays.asList("str1","str2");
- Linearity vs circularity
arr[idx] = element; // Assign the element at the current index idx = idx + 1; // Increment the index linearly until idx reaches arr.length - 1 idx = (idx + 1) % arr.length; // Increment the index circularly. The modulo operator ensures that idx wraps around to 0 when it reaches arr.length
2D Array
- Declare and Iterate through the 2D Array
// Declaring a Rectangular Matrix String[][] arr = new String[6][7]; // 6 rows and 7 columns // Iterating through the 2D array and assigning values for (int i = 0; i < arr.length; i++) { // Loop through rows for (int j = 0; j < arr[i].length; j++) { // Loop through columns arr[i][j] = "-" + i + "_" + j;//Do something } }
- using List of List
// Declaring a 2D Matrix List<List<Integer>> list = new ArrayList<>(); //Adding Elements into 2D ArrayList list.add(0, Arrays.asList(11,12,13)); list.add(1, Arrays.asList(21,22,23)); list.add(2, Arrays.asList(31,32,33)); //Printing the Matrix using FOR Loop for (int i = 0; i < list.size(); i = i + 1) { for (int j = 0; j < list.get(i).size(); j = j + 1) { System.out.print(list.get(i).get(j) + "\t"); } System.out.println(); }
The Arrays Class
int size = 10;//any chosen size
boolean[] arr = new boolean[size];//primitive array : Initialized to False
// Wrapper class array
Boolean[] array = new Boolean[size];//Wrapper Class
Arrays.fill(array, Boolean.FALSE);//Initialize entire Array
int[] intArr = new int[size];// Primitive array: initialized to 0
// Wrapper class array
Integer[] wrapperIntArr = new Integer[size];
Arrays.fill(wrapperIntArr, Integer.valueOf(0)); // Initialize entire array to 0
Copying and Comparing Arrays
int[] original = {1, 2, 3, 4, 5};
// Copy array
int[] copy = Arrays.copyOf(original, original.length);
// Compare arrays
boolean areEqual = Arrays.equals(original, copy);
Sorting
String[] stringArr = new String[5];
Arrays.fill(stringArr, "Default Value");// Initialize all elements
stringArr[2] = "Custom Value"; // Replacing specific elements
// Sorting the array
Arrays.sort(stringArr);//returns void, Changes the original array
Maps
- contains key or value
boolean containsValue = map.containsValue(3); boolean containsKey = map.containsKey("Harry");// returns true if the key is in the map, false otherwise
- getOrDefault
Map<String,Integer> map = new HashMap<>(); for (String str: list){//Considering a list of Strings // Use getOrDefault to fetch the current count (default to 0 if the key is not present) int count = map.getOrDefault(str, 0); map.put(str, count + 1); // Increment the count and update the map }
- Traditional
for (String str: namesList) { if(treeMap.containsKey(str)) treeMap.put(str, map.get(str) + 1); else treeMap.put(str,1); }
- put key-value
Map<Integer,Integer> map = new HashMap<>(); map.putIfAbsent(key, value); map.put(1, 100); //Inserts the key-value pair (1, 100) map.put(1, 200); //Updates the value associated with key 1 to 200, returns 100 map.putIfAbsent(1, 100); //Inserts the key-value pair (1, 100) map.putIfAbsent(1, 200); //Does nothing because key 1 already exists, returns 100
- Remove from Map
/* removes the key/value pair for this key if present. Does nothing if the key is not present. */ map.remove(key); //Concurrent Modification Exception in a Loop itr.remove(); //used to avoid concurrent modification exception using an Iterator
Map Iterator
-
map.keySet().iterator()
Iterator<String> itr = map.keySet().iterator();//Returns iterator to all the keys while (itr.hasNext()) { String key = itr.next(); Integer value = map.get(key); }
-
map.entrySet()
- The
entrySet()
method of a Map returns a set of all thekey-value
pairs in the map. - Each pair is represented as a
Map.Entry<K, V>
object, where K is the key type and V is the value type. -
Map.Entry<KeyType, ValueType> entry : map.entrySet()
// Iterate over the map using entrySet() for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); }
- The
- map forEach - Takes in a BiConsumer (key,value)
treeMap.forEach((key, value) -> System.out.println(key + "->" + value));
TreeMap with Comparator
Tree map keeps the Default Natural Sorting Order with the Keys
Map<String, Integer> treeMap = new TreeMap<>();//Default Natural Sorting Order
Map<String, Integer> treeMapReversed =new TreeMap<>(Comparator.reverseOrder());
Map<String, Integer> treeMapCustom = new TreeMap<>(Comparator.comparing(String::length));//Custom key sorter
for (String name : namesList) {//From a list of Strints, put String as key
treeMap.put(name, name.length());
}
Character
- primitive to Wrapper
Character d = Character.valueOf('c');//From primitive to Wrapper
- get ascii value of a character
char myChar = 'a'; int asciiValue = myChar; System.out.println("From type Casting "+asciiValue);
- get int from char (with numerical value) with
-'0'
char charNum2 = '2'; int num2 = charNum2 - '0';
-
Character.isLetterOrDigit()
checks for punctuation marks orSystem.out.println(Character.isLetter('r'));//true 'r' is a letter System.out.println(Character.isDigit('4'));//true System.out.println(!Character.isLetterOrDigit('!'));//true : punctuation mark System.out.println(Character.compare('1','1'));//Compare character
- int array to keep char ascii as index and array value as count. Use of HashMap
can be avoided to keep the count.
int[] chars = new int[127];//primitive int array initializes all the values with 0 char test = 'a'; chars[test]++; chars['A']++; System.out.println(Arrays.toString(chars));//The value of Array at index = asciiVal of char is increased by 1 /* [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ##1##, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,##1##, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] */
-
getNumericValue()
returns Integer value from character// Same can be achieved through the library method //Returns unicode for characters from 10 to 35 System.out.println(Character.getNumericValue('A'));//DO NOT USE THIS System.out.println(Character.getNumericValue(myChar)); System.out.println(Character.getNumericValue('1'));
String
- length(), equals() & str.compareTo(“”);
str1.equals(str2);//For Equality, DO NOT USE == (will compare objects)
str1.compareTo(str2);
// negative if str is "lexicographically" less than str2
// positive if str is "lexicographically" greater than str2
// ZERO is both strings are equal
- isBlank()
System.out.println(" ".isBlank());//True -> Returns true if the string is empty or contains only white space
- split()
//Cut the Strings from spaces into a words
String[] words = strList.split(",");
- trim() and strip()
String s = " Malgudi Days ";
System.out.println(s.trim());//Trimmed blank spaces with all leading and trailing space removed
System.out.println(s.strip());//Strip is Unicode Aware
System.out.println(s.stripLeading());
System.out.println(s.stripTrailing());
- contains
String sentence = "Hello, world!";
// Check if the string contains a specific substring
boolean containsHello = sentence.contains("Hello");
- charAt & substring()
//returns a character at a given index i str.chatAt(i); str.substring(i,j);//index j not included str.substring(i);//from i till end
- indexOf & lastIndexOf
//2 if "er" begins from index 1, -1 if not Found str.indexOf("er"); str.indexOf("er", 2); //start the search from index 2 str.lastIndexOf("ew");//searches right to left str.lastIndexOf("ew", 5);//right to left, from index 5
- case change
str.toLowerCase(); str.toUpperCase();
- compare & replace
System.out.println(str.replace("a","$$")); System.out.println(str.replace('e','*'));//Character Replace String str1 = str.replaceAll(" ", "" );//Replace All, takes RegEx
- String to Char Array to String
String str = "Pneumonia"; char[] c = str.toLowerCase().toCharArray(); Arrays.sort(c);//Returns a void String revStr = new String(c);
- Turn anything into String ```java char c = ‘C’; int d = 5; Integer i = 5; String newStr = String.valueOf(i));
char[] c = {‘T’,’e’,’s’,’t’}; String newStr = String.valueOf(c);
# Sorting
All sorts (`Arrays.sort`, `listObj.sort`, `Collections.sort`)
- returns void
- changes the input array
### Arrays Sort
```java
int[] intArray = {4,5,3,8,2,71};
Arrays.sort(intArray);//Default Natural Sorting Order
Arrays.sort(intArray, Comparator.reverseOrder());//Reverse sorting
List Sort
-
Comparator.nullsFirst()
orComparator.nullsLast()
can be used to accommodate null values.
List<Integer> list = Arrays.asList(null,4,5,null,3,8,2,71,null);
list.sort(Comparator.nullsLast(Comparator.naturalOrder()));
list.sort(Comparator.nullsFirst(Comparator.reverseOrder()));
List<String> stringList = Arrays.asList("apple", "banana", "orange");
stringList.sort(Comparator.comparing(String::length).reversed());
Collections sort
- takes care of arranging the
null
values -
List<Integer> integerListWithNull = Arrays.asList(5, 6, null, 71, 2, 3); Collections.sort(integerListWithNull, Comparator.nullsLast(Comparator.naturalOrder())); Collections.sort(integerListWithoutNull, Collections.reverseOrder()); List<String> stringList = Arrays.asList("apple","banana", "orange"); Collections.sort(stringList, Comparator .comparing(String::length) .thenComparing(Comparator.reverseOrder()));
Set
List<String> namesList = Arrays.asList("Harry", "Hermione", "Ron","Harry", "Ron", "Ron", "Remus");
// Sorted values returned while iterating in TreeSet
Set<String> treeSet = new TreeSet<>(Comparator.reverseOrder());
treeSet.addAll(namesList);
// Ordering NOT guaranteed in HashSet
Set<Integer> set = new HashSet<Integer>();
- Add elements in a Set
/* Adds the element to the set and returns true if this set does not have this element. if the element already exist the call leaves the set unchanged and returns false*/ set.add(value); //boolean add(E e);
- Find an element in a set
/* returns true if the key is in the map, false otherwise.*/ set.contains(key);
- remove from Set
boolean remove(Object o) // Removes the specified element from this set if it is present. Returns true if this set contained the element set.remove(key);// Concurrent Modification Exception in a Loop itr.remove();// use of Iterator to avoid conc. modi. excep.
Set Iteration
Iterator<String> itr = set.iterator();
while(itr.hasNext()){
if(itr.next().length()%2 == 0){
itr.remove();
}
}
Heap
- Declaring min and max heaps
// Primitive Types Queue<Integer> pq = new PriorityQueue<>();//Default Natural Sorting Order Queue<Integer> pq = new PriorityQueue<>(Comparator.naturalOrder());//Min Heap Queue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());//Max Heap
-
poll()
to pop the element out//Heap methods pq.offer(100); pq.poll();//pops the root of the heap
- Heap/Priority Queue of Type T
//For Type T Queue<Employee> heapMax = new PriorityQueue<>(Comparator.comparing(Employee::getAge)//If the employee age is same .thenComparing(Employee::getSalary));//Natural Sort Order
Queue
- offer() Enqueue (add) elements to the queue**
- peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
- poll() Retrieves and removes the head of this queue, or returns null if this queue is empty.
- remove() Removes a single instance of the specified element from this queue, if it is present.
- element() Retrieves, but does not remove, the head of this queue, differs from peek -> throws an exception if queue is empty.
// Declare a queue using LinkedList
Queue<String> queue = new LinkedList<>();
// Enqueue (add) elements to the queue
queue.offer("Apple");
queue.offer("Banana");
queue.offer("Orange");
Stack
- push(E item): Pushes an item onto the top of the stack.
- pop(): Removes the object at the top of the stack and returns that object.
- peek(): Looks at the object at the top of the stack without removing it.
- empty(): Checks if the stack is empty.
- search(Object o): Searches for the specified object in the stack and returns its position.
Stack<Integer> stack = new Stack<>();
stack.push(1); stack.push(2);stack.push(3);
System.out.println("Top element: " + stack.peek()); // Output: 3
while (!stack.empty()) {
System.out.println("Popped element: " + stack.pop());
}
// This Does not work as stack.pop reduces the size of the stack each time
for (int i = 0; i < stack.size(); i++) {
System.out.println(stack.pop());
}
Math
- min & max
int maxNumber = Math.max(10, 20); float maxFloat = Math.max(15.5f, 12.7f); int minNumber = Math.min(10, 20); float minFloat = Math.min(15.5f, 12.7f);
- power and square root
double powerIntResult = Math.pow(2, 3); double powerFloatResult = Math.pow(2.5, 2); double sqrtResult = Math.sqrt(25);
- absolute
int absoluteIntValue = Math.abs(-5); float absoluteFloatValue = Math.abs(-8.9f);
- ceil and floor
double ceilIntResult = Math.ceil(5.3); float ceilFloatResult = (float) Math.ceil(5.3f); double floorIntResult = Math.floor(5.9); float floorFloatResult = (float) Math.floor(5.9f);
- log
double log10IntResult = Math.log10(1000); double log10FloatResult = Math.log10(1000.0f); double logResult = Math.log(Math.E); // Log base e of e is 1
Bitwise
-
Left Shift (<<)
: Shifts the bits to the left by a specified number of positions (n) value « n.- The vacant positions on the right are filled with zeros.
- it effectively multiplies the operand by
2^n
-
Signed Right Shift (>>)
: Shifts the bits of the operand to the right by a specified number of positions.- It fills the vacant positions on the left with the sign bit (the leftmost bit) to preserve the sign of the number.
- If the number is positive, it fills with 0, and if negative, it fills with 1.
-
Divides the number by
2^n
-
Unsigned Right Shift (>>>)
- It fills the vacant positions on the left with zeros, regardless of the sign bit.
- It is used for logical right shifts, and it treats the operand as an unsigned quantity.
- ALWAYS use this for the while loop, else infinite loop for negative numbers
-
Bit representation
short x = 0b11101011; Integer.toBinaryString(235)
-
Negative number
int positiveNum= 0b00101100;//44 int twoScomplement = 0b11010100;
-
Extracts the LSB of a number
(number & 1)
-
Clear/Unset the rightmost set bit
x & (x - 1)
-
Extracts the rightmost set bit
x & ~(x - 1)` isolates the rightmost 1-bit of y and sets all other bits to 0
-
Set the Nth bit Bitmask
1 << n
-
XOR #1 Cancels when same
(x^x);//0 (x^(~x));//-1
-
XOR #2 Adding Without Carrying
-
Parity = 1 When #1’s Odd
x = (x & (x-1)); parity = (parity ^ 1);