java -verbose:class -classpath $(echo *.jar | sed ‘s/ /:/g’) com.anything.yourclass | grep “yourclass”- There is no stack interface in Java
- push + pop + peek - are the methods generally used by classes that supports stack functionality (Stack and ArrayDeque)
- offer(e) and offer(e, time, unit) (boolean)
- poll() and poll(time, unit) (returns E or null when timeout)
- put(E e)
- take()
- TREEIFY_THRESHOLD - In Java 8, HashMap replaces the linked list with another useful data structure i.e. binary tree on breaching a certain threshold
- Which is known as TREEIFY_THRESHOLD. Once this threshold is reached the linked list of Entries is converted to the TreeNodes
- which reduces the time complexity from O(n) to O(log(n)).
- Queue
- Exception throwing API
- add(e)
- remove()
- element()
- Special value returning API
- offer(e)
- poll()
- peek()
- Lock-strip segment (before 8)
- First element in each bucket is locked
1. Deque behaves differently based on its interface
2. Stack (Interface)
1. push - addFirst
2. pop - removeFirst
3. peek - getFirst
3. Queue (Interface) - Equivalent Deque Method
1. add(e) - addLast(e)
2. offer - offerLast
3. remove() - removeFirst()
4. poll - pollFirst()
5. element - getFirst()
6. peek - peekFirst- Comparator.comparing(Function.identity())
- Comparator c = String::compareTo
- Comparator that compares Person objects by their last name,
- Comparator byLastName = Comparator.comparing(Person::getLastName);
- Java doesn't support field reference similar to method reference, hence above style comparator may not work for List.val or Node.val
- Java creating composite comparator
- Comparator cmp = Comparator.comparingInt(p -> p.x).thenComparingInt(p -> p.y);
- Comparator.reverseOrder
- Comparator.comparingInt(String::length).reversed()
- // stream is now [test, foo, a], sorted by descending length
- Comparator.comparingInt(String::length).reversed()
- Sort the indices of two dimensional array named intevals: int[][]
Integer[] indices = IntStream.range(0, intervals.length).boxed().toArray(Integer[]::new); Arrays.sort(indices, Comparator.comparingInt( (Integer i) -> intervals[indices[i]][0] ).thenComparingInt((Integer i) -> intervals[indices[i]][1]));
- If type A has method, that accepts type B as parameter, java can convert that method into interface that can accepts type A and B.
- "The type to which the method belongs precedes the delimiter, and the invocation's receiver is the first parameter of the functional interface method"
- State of lambda
- Comparator<? super E>
- Comparator<? super String>
- why?
- Comparator accepts String
- The container types have the same relationship to each other as the payload types do. This is expressed using the extends keyword.
- If Cat extends Pet, then List is a subtype of List<? extends Pet>
- It is read-only
- The container types have the inverse relationship to each other as the payload types do. This is expressed using the super keyword.
- Container type that is acting purely as a consumer of instances of a type
- It can be used to write types into collection
- "PECS" is from the collection's point of view.
- If you are only pulling items from a generic collection, it is a producer, and you should use extends;
- if you are only stuffing items in, it is a consumer and you should use super.
- If you do both with the same collection, you shouldn't use neither extends nor super. You should use simple class/interface (without wildcards)
- What is a producer?
- A producer is allowed to produce something more specific, hence extends, a consumer is allowed to accept something more general, hence super.
- Producer refers to the return type of method.
- What is a consumer?
- Consumer refers to the parameter type of method.
- A nice mnemonic you can use is to imagine returns for extends and accepts for super.
- Tree<? extends T> reads Tree<? returns T>
Integer.compare(int x, int y) //static method
Integer.max(int x, int y) //static method
Integer.min(int x, int y) //static method
Integer.sum(int x, int y) //static method
compareTo(Integer anotherInteger) //instance methodOptional<Integer> result = stack.stream().reduce(Integer::sum);Collections.max(count.entrySet(), Map.Entry.comparingByValue()).getKey();"String".chars().mapToObj(c -> (char)c)"Arrays.stream(new Integer[]{1,2,3,null}).filter(Objects::nonNull).forEach(System.out::println)
Arrays.stream(lists).filter(Objects::nonNull).forEach(pq::offer);stream.anyMatch(Objects::isNull)
stream.anyMatch(x -> x == null)listOfIntegers.stream().mapToInt(Integer::intValue).toArray()String[] stringArray = stringStream.toArray(String[]::new);find . -name \*java | grep -v “test.*est” | xargs grep -A 4 “catch.*xception” > exceptionHandling.txt
grep -A 4 catch.*xception `find . -type f -name \*java | grep -v test` > xception.lognew int[][]{{1, 2}, {3}, {3}, {}}int[][] closestPoints = new int[k][2];
jshell> var t = new int[5][2]
t ==> int[5][] { int[2] { 0, 0 }, int[2] { 0, 0 }, int[ ... 0, 0 }, int[2] { 0, 0 } }Collections.sort(list, Collections.reverseOrder());
- 3 Ways (reduce-lambda, min, reduce+method-reference)
int min = Stream.of(14, 35, -7, 46, 98).reduce(Integer::min).get();
min = Stream.of(14, 35, -7, 46, 98).min(Integer::compare).get();
min = Arrays.stream(nums).reduce(nums[0], (x,y) -> x<y ? x : y ); Iterator lit = obj.descendingIterator();
System.out.println("Backward Iterations");
while(lit.hasNext()){
System.out.println(lit.next());
}public boolean isSorted(String[] words) {
return IntStream.range(0, words.length-1).noneMatch( i -> words[i+1].compareTo(words[i]) < 0 );
}List<String> bonds = Arrays.asList("Connery","Lazenby","Moore", "Dalton", "Brosnan","Craig");
List<String> sortedByNaturalOrder = bonds.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList());- output: sortedByNaturalOrder ==> [Brosnan, Connery, Craig, Dalton, Lazenby, Moore]
List<String> sortedByReverseOrder = bonds.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());- output: sortedByReverseOrder ==> [Moore, Lazenby, Dalton, Craig, Connery, Brosnan]
List<String> sortedByLowerCase = bonds.stream().sorted(Comparator.comparing(String::toLowerCase)).collect(Collectors.toList());- output: sortedByLowerCase ==> [Brosnan, Connery, Craig, Dalton, Lazenby, Moore]
- Note
- The data is not changed to lowercase
- Only while comparing, the Comparator uses toLowerCase of the all the input values
List<String> sortedByLength = bonds.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList());- output: sortedByLength ==> [Moore, Craig, Dalton, Lazenby, Connery, Brosnan]
- Note
- The data is not changed to lowercase
- Only while comparing, the Comparator uses length of the input string values
List<String> sortedByLengthThenByNaturalOrder = bonds.stream().sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder())).
collect(Collectors.toList());- output: sortedByLengthThenByNaturalOrder ==> [Craig, Moore, Dalton, Brosnan, Connery, Lazenby]
naturalOrder()reverseOrder()comparing(Function<? super T,? extends U> keyExtractor)comparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator)comparingDouble(ToDoubleFunction<? super T> keyExtractor)comparingInt(ToIntFunction<? super T> keyExtractor)comparingLong(ToLongFunction<? super T> keyExtractor)nullsFirst(Comparator<? super T> comparator)nullsLast(Comparator<? super T> comparator)
thenComparing(Comparator<? super T> other)thenComparing(Function<? super T,? extends U> keyExtractor)thenComparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator)thenComparingDouble(ToDoubleFunction<? super T> keyExtractor)thenComparingInt(ToIntFunction<? super T> keyExtractor)thenComparingLong(ToLongFunction<? super T> keyExtractor)
- To sort a collection of String based on the length and then case-insensitive natural ordering, the comparator can be composed using following code,
Comparator<String> cmp = Comparator.comparingInt(String::length).thenComparing(String.CASE_INSENSITIVE_ORDER);static <T,U> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor, Comparator<? super U> keyComparator)- Type Parameters:
- T - input type of element to be compared
- U - the type of the sort key
- Parameters:
- keyExtractor - the function used to extract the sort key
- keyComparator - the Comparator used to compare the sort key
- Returns:
- a comparator that compares by an extracted key using the specified Comparator
Comparator<Person> cmp = Comparator.comparing(
Person::getLastName,
String.CASE_INSENSITIVE_ORDER);Comparator<Person> byLastName = Comparator.comparing(Person::getLastName); Map<Integer, List<Integer>> adj = new HashMap<>();
for (int[] edge : edges) {
int a = edge[0], b = edge[1];
adj.computeIfAbsent(a, value -> new ArrayList<Integer>()).add(b);
adj.computeIfAbsent(b, value -> new ArrayList<Integer>()).add(a);
}String.format("%1$10s-%2$-10s-%3$10s-%4$10d","1000",2500,"123",123);
// " 1000-2500 - 123- 123"
String.format("%1$-10s-%2$10s-%3$-10s-%4$10d","1000",2500,"123",123);
// "1000 - 2500-123 - 123"strBuilder.deleteCharAt(strBuilder.length() - 1)
public StringBuilder replace(int start,int end, String str); //end-1 would be the last character affectedStringBuilder.deleteCharAt(sb.length()-1);String[] strings = {"abc", "dbca"};
jshell> String.join(", ", new String[]{"abc", "dbca"})
$16 ==> "abc, dbca"
jshell> " abc ".strip() //stripLeading and stripTrailing - also available
$18 ==> "abc"
jshell> "abc".repeat(3)
$19 ==> "abcabcabc"jshell>"\\mohan\\root".split("\\\\")
$11 ==> String[3] { "", "mohan", "root" }
jshell> System.out.print("\nmohan\nroot")
mohan
root
jshell> "/a/b".split("/")
$15 ==> String[3] { "", "a", "b" }java.util.Arrays.binarySearch(sortedArr, index + 1, sortedArr.length, key);
//If return value >=0, we found the key Arrays.sort(int[], Collections.reverseOrder()) // will not work for primitive
Arrays.stream(candidates).boxed().sorted (Collections.reverseOrder()).mapToInt(Integer::intValue).toArray(); List<int[]> common = new ArrayList<int[]>();
return (int[][])common.toArray(new int[common.size()][]);Collections.sort(mergedAccount.subList(1, mergedAccount.size())); private void reverse(int[] nums, int first, int last) {
while (first < last) {
swap(nums, first++, last--);
}
}IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
Collections.reverse(Arrays.asList(yourArray));Integer sum = integers.stream().reduce(0, Integer::sum);
return (int)freq.values().stream().filter( v -> v>=2).count(); IntStream.rangeClosed(1, 10).flatMap(i -> IntStream.rangeClosed(1, i)).boxed().collect(Collectors.toList());word1FrequencyList.equals(word2FrequencyList);
Arrays.equals(array1, array2);
Deque<String> deque = new ArrayDeque<String>();deque.push("1");deque.push("2");
for(String data: deque) { System.out.println(deque.remove());} //2 and 1
for(String data: deque) { System.out.println(data);} //2 and 1- Deque-API
- Deque: ![Alt Text][DequeImage]
Deque<String> deque = new ArrayDeque<String>();deque.push("1");deque.push("2");
while(!deque.isEmpty()) { System.out.println(deque.removeLast());} //1,2- Collector<T,?,Map<K,U>>
toMap(Function<? super T,? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction)
toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)- Map.Entry.comparingByValue()
- Map.Entry.comparingByValue(Comparator.reverseOrder())
- Map.Entry.comparingByKey()
- Map.Entry.comparingByKey(Comparator.reverseOrder())
- Can be used only when containers are sorted
List<Dish> slicedMenuDishes = specialMenu.stream()
.takeWhile(dish -> dish.getCalories() < 320)
.collect(toList());
List<Dish> slicedMenuDishes = specialMenu.stream()
.dropWhile(dish -> dish.getCalories() < 320)
.collect(toList());jshell https://kishida.github.io/misc/jframe.jshell
jshell https://gist.githubusercontent.com/mohanmca/88de9d6115587f9b8c6e8ac73b80f46e/raw/a6f272479026f8bb5d79f01f9cbab631e04cb78c/jshell.jshell @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Order order = (Order) o;
return quantity == order.quantity
&& Float.compare(order.price, price) == 0
&& orderedTime == order.orderedTime
&& arrivedTime == order.arrivedTime
&& Objects.equals(orderId, order.orderId)
&& Objects.equals(parentOrderId, order.parentOrderId)
&& side == order.side && Objects.equals(instrument, order.instrument);
}
@Override
public int hashCode() {
return Objects.hash(orderId, parentOrderId, side, instrument, quantity, price, orderedTime, arrivedTime);
}- aruld/java-oneliners
- java-8-stream-cheat-sheet
- Java collections cheat sheet
- Java Generics Cheat sheet
- Java cheatsheet [DequeImage]: img/ArrayDeque.png "ArrayDeque"
- mdanki java_oneliner.md Java_OneLiner.apkg --deck "Mohan::Core::Java::OneLiner"
- node /Users/alpha/.nvm/versions/node/v16.5.0/lib/node_modules/mdanki/src/index.js java_oneliner.md Java_OneLiner.apkg --deck "Mohan::Core::Java::OneLiner" -s TOTAL_MEMORY=26777216