Java Tricks

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

1. String s = sc.nextLine().

toLowerCase();

String [] str = s.split(" ");


It will split the line by a space and create a array of string

2. While creating function always create outside the main function by using public static return
type function name
3. To get the ith index of string use str.chatAt(i)
4. To get the length of string use str.length() and for array use arr.length
5. To convert a char to int use : int p = Integer.parseInt(String.valueOf(s.charAt(i)));
6. Array declaration
int n=s.length();
int [][]t=new int[n][n];
to get the max and min use Math.max(a,b);
7. String str = "chandrabhushan"; // Convert string to a character array char[] charArray =
str.toCharArray(); // Sort the character array Arrays.sort(charArray);
8. To check weather a charestor is int or not use Charecter.isDigit(ch);
9. Arrays.toString() is a static method in the java.util.Arrays class that provides a simple way to print
an array in a human-readable format. Instead of printing the memory reference of the array, it
converts the elements of the array into a string representation.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(numbers)); // op: [1, 2, 3, 4, 5]
10. To sort the array using opposite way we can use:
Coparator.reverseOrder();
i.e : Collections.sort(list,Comparator.reverseOrder());

double d = 123.4567;

System.out.format("%.3f\n", d);

String formatted = String.format("%.2f", d);

d = Double.parseDouble(formatted);

System.out.println(d);

BigInteger b,a;

b = BigInteger.valueOf(4);

a = BigInteger.valueOf(6);

System.out.println(b);

BigInteger c = b.add(a);
BigInteger d = a.multiply(b);

System.out.println(d);

System.out.println(c);

//Similarly we have BigDecimal for large floating point number;

Arrays Class
Commonly Used Methods in the Arrays Class

Sorting Arrays:

Arrays.sort(array): Sorts the specified array into ascending numerical order.

Arrays.sort(array, fromIndex, toIndex): Sorts the specified range of the array into ascending
order.

Searching Arrays:

 Arrays.binarySearch(array, key): Searches the specified array for the specified value using the
binary search algorithm. The array must be sorted.

Filling Arrays:

 Arrays.fill(array, value): Assigns the specified value to each element of the specified array.

 Arrays.fill(array, fromIndex, toIndex, value): Assigns the specified value to each element of the
specified range of the array.

Copying Arrays:

 Arrays.copyOf(original, newLength): Copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.

 Arrays.copyOfRange(original, from, to): Copies the specified range of the specified array into a
new array.

Comparing Arrays:

 Arrays.equals(array1, array2): Returns true if the two specified arrays are equal to one another.

 Arrays.deepEquals(array1, array2): Returns true if the two specified arrays are deeply equal to
one another (used for nested arrays).

Converting Arrays to String:

 Arrays.toString(array): Returns a string representation of the contents of the specified array.

 Arrays.deepToString(array): Returns a string representation of the deep contents of the specified


array (used for nested arrays).
Collections class
List<String> list = new ArrayList<>(Arrays.asList("Banana", "Apple", "Cherry")); Collections.sort(list);

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

Collections.shuffle(list);

System.out.println(list); // Output: A shuffled list, e.g., [3, 5, 1, 4, 2]

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

Collections.reverse(list);

System.out.println(list); // Output: [5, 4, 3, 2, 1]

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

int min = Collections.min(list);

System.out.println("Min: " + min); // Output: Min: 1

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

int max = Collections.max(list);

System.out.println("Max: " + max); // Output: Max: 5

List<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Apple", "Cherry", "Apple"));

int frequency = Collections.frequency(list, "Apple");

System.out.println("Frequency of 'Apple': " + frequency); // Output: Frequency of 'Apple': 3

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

int index = Collections.binarySearch(list, 3);

System.out.println("Index of 3: " + index); // Output: Index of 3: 2

List<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));

Collections.fill(list, "Date");

System.out.println(list); // Output: [Date, Date, Date]

List<String> list1 = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry"));

List<String> list2 = new ArrayList<>(Arrays.asList("Date", "Fig", "Grape"));

boolean isDisjoint = Collections.disjoint(list1, list2);

System.out.println("Is disjoint: " + isDisjoint); // Output: Is disjoint: true

List<String> list = new ArrayList<>();

Collections.addAll(list, "Apple", "Banana", "Cherry");


System.out.println(list); // Output: [Apple, Banana, Cherry]

Collections & Framewords:


1. ArrayList
ArrayList<String> list = new ArrayList<>();
// Convert the HashSet to an ArrayList
HashSet<String> set = new HashSet<>();
ArrayList<String> list = new ArrayList<>(set);
Similarly we can convert form other data structure to arrayList;
Add: list.add("Apple");
Accessing elements (using index): String fruit = list.get(0);
Or using for each : for(String ele: list)
{sout(ele)}
Using Iterator :
Iterator<Integer> it = list.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}

Updating an element: list.set(1, "Orange"); // Replaces "Banana" with


"Orange"
Removing an element: list.remove(2); // Removes the element at index 2
(Mango)
Remove element using value: list.remove(Integer.valueOf(“Orange”))
Contains of Not: list.contains(“Apple”);
Getting size: int size = list.size(); // Returns the number of elements in
the list
clear(): Removes all elements from the list.
isEmpty(): Checks if the list is empty.

2. Stack
push(element): Adds an element to the top of the stack.

 pop(): Removes and returns the top element of the stack. Throws an EmptyStackException if the stack
is empty.

 peek(): Returns the top element without removing it. Also throws an EmptyStackException if empty.

 isEmpty(): Checks if the stack is empty, returning true if so, and false otherwise.

 search(object): Searches for an element and returns its 1-based position from the top. Returns -1 if the
element isn’t found.

3. Queue
Queue<Integer> queue = new LinkedList<>();
 add(element): Inserts an element at the end of the queue. Throws an exception if the queue
is full.
 offer(element): Similar to add, but returns false if the queue is full rather than throwing an
exception.
 remove(): Removes and returns the front element. Throws a NoSuchElementException if the
queue is empty.
 poll(): Removes and returns the front element, or returns null if the queue is empty.
 peek(): Retrieves, but does not remove, the front element. Returns null if the queue is empty.
 element(): Similar to peek(), but throws a NoSuchElementException if the queue is empty.

4. PriorityQueue
Min-heap: PriorityQueue<Integer> pq = new PriorityQueue<>();
Max-heap: PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());

 add(element) / offer(element): Inserts an element into the queue in the correct order.

 peek(): Retrieves, but does not remove, the head of the queue (smallest or highest-priority element).

 poll(): Retrieves and removes the head of the queue. Returns null if the queue is empty.

 remove(): Removes a specific element if present.

5. ArrayDeque
1. Adding Elements
 addFirst(E e): Adds the specified element at the front of the deque.
 addLast(E e): Adds the specified element at the end of the deque.
 offerFirst(E e): Inserts the element at the front; returns true if successful, false if not.
 offerLast(E e): Inserts the element at the end; returns true if successful, false if not.
 push(E e): Adds the element at the front of the deque (for stack functionality).
 offer(E e): Adds the element to the end (same as offerLast).
2. Removing Elements
 removeFirst(): Removes and returns the first element. Throws an exception if the deque is
empty.
 removeLast(): Removes and returns the last element. Throws an exception if the deque is empty.
 pollFirst(): Removes and returns the first element, or returns null if the deque is empty.
 pollLast(): Removes and returns the last element, or returns null if the deque is empty.
 pop(): Removes and returns the first element (for stack functionality). Throws an exception if the
deque is empty.
 poll(): Removes and returns the first element (same as pollFirst).
3. Accessing Elements
 getFirst(): Retrieves, but does not remove, the first element. Throws an exception if the deque is
empty.
 getLast(): Retrieves, but does not remove, the last element. Throws an exception if the deque is
empty.
 peekFirst(): Retrieves, but does not remove, the first element, or returns null if the deque is
empty.
 peekLast(): Retrieves, but does not remove, the last element, or returns null if the deque is
empty.
 peek(): Retrieves, but does not remove, the first element (same as peekFirst).
4. Checking Elements
 contains(Object o): Checks if the deque contains the specified element, returning true if it does,
false otherwise.
 isEmpty(): Checks if the deque is empty, returning true if it has no elements, false otherwise.

6. Set
Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>();
Set<String> linkedHashSet = new LinkedHashSet<>();
Types of Sets in Java
1. HashSet:
o Does not maintain any order of elements.
o Allows null elements.
o Fastest for basic operations (add, remove, contains).
o Backed by a hash table, so the order is unpredictable.
2. LinkedHashSet:
o Maintains insertion order.
o Allows null elements.
o Slightly slower than HashSet due to the ordering overhead.
o Useful when you need a set that keeps elements in the order they were added.
3. TreeSet:
o Maintains elements in sorted (ascending) order.
o Does not allow null elements.
o Implements NavigableSet and is backed by a Red-Black tree.
o Useful when you need elements to be sorted automatically

HashSet<String> set = new HashSet<>();

Add elements: set.add("Apple");

Check if an element exists: set.contains(“Apple”);


Remove: set.remove("Cherry");

size(): Returns the number of elements in the set.

isEmpty(): Returns true if the set is empty.

clear(): Removes all elements from the set.

Traversing hashSet

for (String fruit : set) { System.out.println(fruit); }

or

Iterator<String> iterator = set.iterator();

while (iterator.hasNext()) {

String fruit = iterator.next();

System.out.println(fruit);

7. Map
Map<String, Integer> map = new HashMap<>();
// Adding key-value pairs to the HashMap map.put("Apple", 10);
// Accessing values based on keys System.out.println("Value for key 'Apple': " +
map.get("Apple"));
// Checking if a key exists if (map.containsKey("Banana")) { System.out.println("The
map contains key 'Banana'."); }
// Iterating over the map for (Map.Entry<String, Integer> entry : map.entrySet())
{ System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); }
// Removing a key-value pair map.remove("Orange");
// Size of the map System.out.println("Size of the map: " + map.size());

Other Implementations of Map


 LinkedHashMap: Maintains insertion order.
 TreeMap: Maintains a sorted order of the keys

int value = map.get("Apple");


System.out.println("Value for Apple: " + value); // Output: Value for Apple: 10

boolean hasValue10 = map.containsValue(10);


System.out.println("Contains value 10: " + hasValue10); // Output: Contains value 10:
true

map.put("Banana", 20);
Set<String> keys = map.keySet();
System.out.println("Keys: " + keys); // Output: Keys: [Apple, Banana]

Collection<Integer> values = map.values();


System.out.println("Values: " + values); // Output: Values: [10, 20]

map.replace("Apple", 15);
System.out.println(map.get("Apple")); // Output: 15

map.replace("Banana", 20, 25);


System.out.println(map.get("Banana")); // Output: 25

map.getOrDefault is a method in Java’s Map interface that allows you to retrieve the
value associated with a specific key, or return a default value if the key doesn’t exist in
the map. This can be useful to avoid NullPointerException or needing to check for the
key’s existence before accessing it.
Map<String, Integer> map = new HashMap<>(); map.put("apple", 3);
map.put("banana", 2); // Existing key int appleCount = map.getOrDefault("apple",
0); // Returns 3 System.out.println("Apple count: " + appleCount); // Non-existing key
int orangeCount = map.getOrDefault("orange", 0);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy