Built-in methods
Sort
/***** Primitive *****/
import java.util.Arrays;
int[] nums
Arrays.sort(nums); // Ascending - No buit-in
/***** List *****/
import java.util.Collections;
import java.util.Comparator;
List<Integer> nums;
Collections.sort(nums); // Ascending
Collections.sort(nums, Comparator.reverse()) // Descending
Flatmap
Flattens out the inner list of properties of a list of object. For example if we have a list of User and every user has a list of Address, we can flatten out the addresses:
static class Address {
public String addy;
public Address(String addy) {
this.addy = addy;
}
}
static class User {
public String name;
public List<Address> addresses;
public User(String name, List<Address> addresses ) {
this.name = name;
this.addresses = addresses;
}
}
public static void main(String[] args) {
User john = new User("john", Arrays.asList(new Address("Arctic"), new Address("Atlantic")));
User bob = new User("bob", Arrays.asList(new Address("Indian"), new Address("Pacific")));
List<User> users = Arrays.asList(john, bob);
List<Address> allAddys = users.stream().flatMap(user -> user.addresses.stream()).toList();
allAddys.stream().map(a -> a.addy).forEach(System.out::println);
}
// Output
Arctic
Atlantic
Indian
Pacific
lowercase, alphanumeric
String s = "Hello";
String lower = s.toLowerCase();
String upper = s.toUpperCase();
Character c = 'c';
Character lower = Character.toLowerCase(c);
Character upper = Character.toUpperCase(c);
Character.isLetter(c);
Character.isDigit(c);
Character.isLetterOrDigit(c);
Stack, Queue
- Stack:
push
peak
top
- Queue:
offer
peak
poll
Stack<Integer> s = new Stack<>();
s.push(1); s.push(2);
// Peek top
int top = s.peek();
// Remove top
top = s.pop();
Queue<Integer> q = new LinkedList<>();
q.offer(1); q.offer(2);
// peak head
int head = q.peek();
// remove head
head = q.poll();