Java code snippet and implementations Flashcards

1
Q

Common implementation for queue

A
  • PriorityQueue - sorts elements in their natural order as they are inserted - don’t use for BFS
  • Linked list - keep the same order as when they are inserted
  Queue<Integer> q = new PriorityQueue<>();
  Queue<Integer> linkedList = new LinkedList<>();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Methods to add and remove items from the queue

A
  • add/remove: throw exception if queue is full
  • offer/poll: returns null if queue is full
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Implementation for a stack

A

Stack<Integer> stack = new Stack<>();</Integer>

  • stack inherits from Vector abstract class

Methods:
- from Stack class
- push/pop
- peek - look w/o popping

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Whats a TreeMap

A
  • items are sorted using their natural order
  • use comparators to define sort order
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Implement a comparator

A
  • return 1 when greater
  • descending order is when o2 > o1

Map<Integer, List<Set<Integer>>> profitToDayIndexMap = new TreeMap<>(</Integer>

// descending order
new Comparator<Integer>() {</Integer>

 @Override
 public int compare(Integer o1, Integer o2) {
       return o2 > o1 ? 1 : o2 == o1 ? 0 : -1;
  }
}  );

Think this way. You are given two items. Return 1 for the item you want the comparator to return first when it’s greater than the other.

For descending order, return 1 when b > a.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Convert array to list and vise verse

A
  • better not use primitive types for easy conversion
  • list <- array:
    • use Arrays.asList(array)
    • and pass the array
  • array <- list
    • use list.toArray(new Integer[0])
    • it’s always new Integer[0]
// init array
Integer[] array = new Integer[]{1, 2, 3};       

// convert array to list
List<Integer> list = Arrays.asList(array);

// convert list to array
array = list.toArray(new Integer[0]);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What Set implementation to use to
1. maintain the insertion order
2. maintain the natural ordering of the elements

A
  • maintain insertion order: LinkedHashSet
  • maintain natural ordering: TreeSet
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Whats the limits to recursion in java

A
  • it’s the overall thread stack size
  • can be tuned via -Xss flag
  • causes stack overflow error if reached
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How to sort an array in place

A

int[] nums = new int[]{2, 3, 5, 1};
Arrays.sort(nums);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How to sort an array w/o modifying the array

A

int[] nums2 = new int[]{2, 3, 5, 1};
int[] sorted = Arrays.stream(nums2).sorted().toArray();

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to sort a list

A

List<Integer> nums = Arrays.asList(1, 4, 3, 2);
List<Integer> sorted = nums.stream().sorted().collect(Collectors.toList());</Integer></Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Name some common methods on the Arrays class

A

These modifies the array in place
- Arrays.sort(array)
- Arrays.binarySearch(sortedArray, value)
- return position of the key or -1 if not found
- Arrays.fill(array, valueToFill)

These allow the array to be viewed and operated on as a list
- Arrays.stream(array)…. // more manipulation
- Arrays.asList(array);
- Arrays.asList(1,2,3);

int[] array = new int[]{1,2,3};

// static method for search
Arrays.sort(nums);
int pos = Arrays.binarySearch(nums, 1);

// static method to fill
Arrays.fill(nums, 1);

// static methods for sort
Arrays.sort(array);   // sorts in place

// allow arrays to be viewed as lists
Arrays.stream(array)...  // view array as a list 

Arrays.asList(1,2,3);       // inits a list with value
Arrays.asList(array);      // inits a list with an array
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are some highlights of the Arrays class

A
  • Arrays is a concrete class
  • Contains methods to manipulate arrays such as sorting and searching
  • Contains static factory to allow arrays to be viewed as lists.
  • sorted() is a method on the Stream interface
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to convert list <-> array with primitive types

A
  • the complication here is because we need to do “boxing”
  • list <- array: use Arrays.stream(array).boxed()
  • array <- list: use mapToInt()
        // with primitive types
        int[] primitiveArray = new int[]{1, 2, 3};

        // convert array to list (where array is with primitive type)
        List<Integer> list2 = Arrays.stream(primitiveArray).boxed().collect(Collectors.toList());

        // convert list to array
        primitiveArray = list2.stream().mapToInt(Integer::intValue).toArray();
        
        primitiveArray = list2.stream().mapToInt(i -> i).toArray();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Collection, Collections, Collector, Collectors, etc

What are the high level differences

A
  • two pairs of class (with s) and interface (w/o s)
  • Collectors: reduction operation: toList, joining, groupingBy
  • Collections: utility (static) methods on Collection (List, Set, Map, Queue)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

For Collection, Collections, Collector, Collectors, etc

What’s “Collectors” (with s)

Name some common operations and how to call it.

A

Collectors (class)

  • Implements the Collector interface (via a static inner class)
  • Implements various reduction operation
    • Collectors.toList()
    • Collectors.toCollection(TreeSet::new) // convert to specific Set implementation
    • Collectors.joining(“,”)
    • Collectors.groupingBy
    • Collectors.partitioningBy
  • to call Collectors, use collect(Collectors.toList())
17
Q

For Collection, Collections, Collector, Collectors, etc

What’s “Collector” (w/o s)

A

Collector (interface)

  • implemented by the “Collectors” class
  • mutable reduction operation
  • accumulates input elements into a mutable result container
  • optionally transform the accumulated result into a final representation and all input elements have been processed
  • reduction operation can be sequential or parallel
18
Q

For Collection, Collections, Collector, Collectors, etc

What’s “Collections” (w/ s)

A

Collections (class)

  • does NOT implement the “Collection” interface itself
  • a utility class to operate on Collection
  • contains all static methods
  • methods such as sort, binarySearch, min, max, replaceAll, reverse, swap
19
Q

What are some useful utility methods on the Collections class

A
  • sort (List<T> list) -> void</T>
  • binarySearch (List<T> list, T key) -> int</T>
  • frequency (Collection<?> c, Object o) -> int
  • fill (List<T> list, T object) -> void</T>
  • min (Collection<T> c) -> T</T>
  • max (Collection<T> c) -> T</T>
  • replaceAll (List<T> list, T oldVal, T newVal) -> boolean
    </T>
    • returns true if at least one element is replaced
  • reverse (List<?> list) -> void
  • shuffle (List<?> list) -> void
  • rotate (List<?> list, int distance) -> void
  • swap (List<?> list, int i, int j) -> void
    • swaps the elements at these indices
        List<Integer> list = Arrays.asList(4, 1, 2, 3);
        Collections.sort(list);
        Collections.fill(list, 3);
20
Q

For Collection, Collections, Collector, Collectors, etc

What’s “Collection” (w/o s)

A

Collection (interface)
- interface for List, Set, Queue, Map etc

21
Q

What’re some differences between Deque vs Stack

A

Deque vs Stack
- Deque is an interfaces implements Queue
- Deque supports insertion/removal from both ends, deque means double ended queue
- Implementing class includes LinkedList
- Stack is a class implementing Vector
- Stack is synchronized (thread-safe) while Dequeue is not
- Dequeue is faster because it’s not synchronized

22
Q

Common methods for Deque

A

Common methods for Deque
- addFirst/addLast, removeFirst/removeLast
- offerFirst/offerLast, pollFirst/pollLast
- peakFirst/peakLast, getFirst/getLast

23
Q

Stream interface and Streams class

A
  • produces a sequence of elements
  • supports aggregate operations
  • aggregation can be sequential or parallel
  • a Stream is created via Collection (list.stream())
  • need to find out how Collection.stream() relates to the Stream interface

  • the class itself is deprecated
  • the stream() methods we normally use are either from Collection.stream() (w/o param) or Arrays.stream(array) (with param)
24
Q

Differences/similarities in methods between Arrays vs Collections

A
  • Collections has min() and max() while Arrays does not
  • Neither has sum()
  • both has binary search and sort
25
Q

Whats the name of the compare function for Comparator and Comparable.

What are some similarities and differences.

A

Comparator
Function: compare. Takes two args

Comparable
Function: compareTo. Take one arg

Both return 1 for the greater element.

Comparable is the interface to implement to be able to sort