Skip to content

Latest commit

 

History

History
264 lines (199 loc) · 9.72 KB

File metadata and controls

264 lines (199 loc) · 9.72 KB

Java Utilities & Collections

Table of contents

Common Utility Methods

String Class

  • it is a reference type
  • strings are immutable (we cant change the string)
  • any methods that changes a string returns a new string
Method Purpose Example
trim() Removes leading and trailing spaces " Hello ".trim()"Hello"
toLowerCase() Converts string to lowercase "HELLO".toLowerCase()"hello"
toUpperCase() Converts string to uppercase "hello".toUpperCase()"HELLO"
replace(old,new) Replaces characters or strings "Hello!".replace("!","*")
replaceAll(regex,new) Replaces using regex pattern "Hello!!".replaceAll("!!","**")
indexOf(val) Returns index of first occurrence "Hello".indexOf("o")4
indexOf(str) Returns starting index of substring "Hello".indexOf("He")0
length() Returns string length "Hello".length()5
startsWith(str) Checks if string starts with value "Hello".startsWith("He")
endsWith(str) Checks if string ends with value "Hello".endsWith("lo")
equals(str) Compares string values "Hello".equals("Hello")
substring(start,end) Extracts part of string "Hello".substring(1,4)"ell"
substring(start) Extracts from index → end "Hello".substring(2)"llo"
repeat(n) Repeats string n times "0".repeat(3)"000"

Integer Class

Method Purpose Example
Integer.toString(num) Converts integer → string Integer.toString(1234)"1234"
Integer.toBinaryString(num) Converts integer → binary string Integer.toBinaryString(5)"101"
Integer.parseInt(str) Converts string → integer Integer.parseInt("11")11
Integer.parseInt(str, radix) Converts number in base → decimal Integer.parseInt("1101",2)13

Math Class

Method Purpose Example
Math.max(a,b) Returns the larger of two numbers Math.max(1,2)2
Math.floor(num) Returns largest integer ≤ number Math.floor(4.9)4.0
Math.ceil(num) Returns smallest integer ≥ number Math.ceil(4.1)5.0
Math.abs(num) Absolute value Math.abs(-5)5
Math.pow(a,b) a raised to power b Math.pow(2,3)8.0
Math.sqrt(num) Square root Math.sqrt(16)4.0
Math.round(num) Rounds to nearest integer Math.round(4.6)5

Character Class

Method Description Example
Character.isLetter(c) Checks if character is a letter Character.isLetter('A')true
Character.isDigit(c) Checks if character is a digit Character.isDigit('5')true
Character.toLowerCase(c) Converts character to lowercase Character.toLowerCase('A')'a'
Character.toUpperCase(c) Converts character to uppercase Character.toUpperCase('z')'Z'
Character.getType(c) Returns integer representing character type Character.getType('A')1

String & Array Conversion

Method Purpose Example
toCharArray() convert string → char array char[] arr = s.toCharArray();
new String(char[]) char array → string String s = new String(arr);
String.valueOf() primitive → string String s = String.valueOf(123);

Escape Sequence

String s = "I'm \n \"Escape Sequence\" \t C:\\Windows";
System.out.println(s);

Constants

  • to declare a constant we user final keyword
final float pi = 3.14F; // if we don't declare F it is seen as decimal
System.out.println("Pi is " + pi); // Pi is 3.14

Casting

  • Implicit Casting (no data loss): byte > Short > int > long > float > double
short x = 1;
int y = x + 1; // implicit casting
System.out.println(y);
  • Explicit Casting (data loss): double > float > long > int > char > short > byte
double x = 1.1;
int y = (int)x + 2; // Explicit casting
System.out.println(y); // 3

Order of operations

() -> */ -> +-

Java Arrays

  • method overloading: multiple methods with the same name but different parameter (Ex: Arrays.toString())
  • method overridding: the method of the subclass class overrides the method of the superclass
Single Dimension Array:

    int[] numbers = new int[5]; // declaration - uninitialized values: 0
    int[] numbers = new int[]{3,4}; // declaration and initialization (Shouldn't declare the size to initialize)
    int[] numbers = {2,3,4,1,5};
    System.out.println(Arrays.toString(numbers)); // [2, 3, 4, 1, 5]
    Arrays.sort(numbers);
    System.out.println(Arrays.toString(numbers)); // [1, 2, 3, 4, 5]

Multi Dimension Array:

    int[][] numbers = new int[][]{{1,2,3},{0,0,0}};
    System.out.println(Arrays.deepToString(numbers)); // [[1, 2, 3], [0, 0, 0]]
    int[][] multiArray = {{1,2},{0,0,0}};
    System.out.println(Arrays.deepToString(multiArray)); // [[1, 2], [0, 0, 0]]
    int[][] multiArray2 = new int[2][3];
    System.out.println(Arrays.deepToString(multiArray2)); // [[0, 0, 0], [0, 0, 0]]
  • Static return
return new int[] {1,2,3};
  • Methods
Method Description Example
length Returns size of array arr.length
sort(arr) Sorts array in ascending order Arrays.sort(arr)
equals(arr1,arr2) Checks two arrays are equal Arrays.equals(arr1,arr2)
toString(arr) Converts array to string Arrays.toString(arr)
deepToString(arr) Converts multi-dimension array to string Arrays.deepToString(numbers)

(back to top)


Collections

ArrayList

  • dynamic array, not synchronized not suitable when multiple threads are accessing it simultaneously

  • Declaration

ArrayList<int[]> ans = new ArrayList<int[]>(); we should pass non primitive data type
ArrayList<Integer> al = new ArrayList<>(10); we added 10 as capacity
ArrayList <Integer> al2 = new ArrayList<>(Arrays.asList(1,2,3));
  • Methods
Method Description Example
add(val) Adds element to end of list al.add(10);
add(index, val) Inserts element at specified index al.add(1, 20);
get(index) Returns element at index al.get(0);
set(index, val) Updates element at index al.set(0, 99);
remove(index) Removes element at index al.remove(2);
contains(val) Checks if list contains element al.contains(50);
size() Returns number of elements al.size();
clear() Removes all elements al.clear();
toArray() Converts list to array al.toArray();
isEmpty() Checks if list is empty al.isEmpty();
indexOf(val) Returns index of first occurrence al.indexOf(99);
lastIndexOf(val) Returns index of last occurrence al.lastIndexOf(99);
addAll(Arrays.asList(arr)) Adds array elements to ArrayList list.addAll(Arrays.asList(arr));
addAll(list) Adds elements from another list list.addAll(list2);
al.stream().mapToInt(i -> i).toArray() Converts ArrayList<Integer> to int[] int[] arr = al.stream().mapToInt(i -> i).toArray();
Collections.reverse(list) Reverses list order Collections.reverse(list);

(back to top)


Vector

  • synchronized, thread-safe, but slower than ArrayList

  • Declaration

Vector<Integer> v = new Vector<Integer>();
  • Methods

📘 Vector – Useful Methods

Method Description Example
add(val) Adds element to end v.add(10);
add(index, val) Inserts element at index v.add(1, 20);
get(index) Gets element at index v.get(0);
set(index, val) Updates element at index v.set(0, 50);
remove(index) Removes element at index v.remove(2);
size() Returns number of elements v.size();
contains(val) Checks if value exists v.contains(100);
clear() Removes all elements v.clear();
addAll(Collection) Adds all elements from another collection v.addAll(list);
elementAt(index) Gets element at index (legacy method) v.elementAt(0);
firstElement() Returns first element v.firstElement();
lastElement() Returns last element v.lastElement();

(back to top)


HashMap

  • A HashMap is a data structure that stores key-value pairs.

  • Declaration

HashMap<Integer,Integer> store = new HashMap<>();
  • Methods
Method Description Example
put(key, value) Inserts or updates a key-value pair map.put(1, 100);
get(key) Returns the value for the key or null if not found map.get(1);
containsKey(key) Checks if the map contains the key map.containsKey(1);
remove(key) Removes key-value pair for the given key map.remove(1);
size() Returns number of key-value pairs map.size();
clear() Removes all mappings map.clear();
isEmpty() Checks if the map is empty map.isEmpty();
keySet() Returns a Set view of keys map.keySet();
values() Returns a collection of values map.values();
entrySet() Returns a Set of key-value pairs map.entrySet();
for-each (entrySet) Iterate through map entries for(Map.Entry<Integer,Integer> e : map.entrySet()) { e.getKey(); e.getValue(); }
sort by value Sort map entries by value list.sort((a,b) -> b.getValue() - a.getValue());

(back to top)