## Basics

### Variables and Types

Principles

• Member Variables should using wrapper types for fields. E.g. Integer, Long.

#### Initialize variables

• Primitive types
• Strings and arrays
• List
• Set
• Maps

#### Initialize constants

• Primitive types
• Strings and Arrays
• Immutable List
• Immutable Set
• Immutable Map

#### Enumeration Type vs Constants

• If number of a set of constant is fixed, you should use enum type.
• If number of a set of constant is increasing and variable, you should use constant variables.

## Core

### Container

#### Basics

1. forEach() vs stream()

If you just want to consume list, you best to choose forEach(), else stream().

#### Remove elements from collection

1. Collect objects set and removeAll()
• Swap position of elements and create new collection copy from updated old collection. Don’t reorganize the collection.
• T(n) = O(n), S(n) = O(n)

1.2 Collect indexes and remove one by one

• T(n) = O(n), S(n) = O(m * n)

1.3 Collect objects set and remove one by one

• T(n) = O(n), S(n) = O(m * n)
1. Using iterator
• Iterator using the cursor variable to traverse collection and remove by index of collection. If you remove a element, the cursor will update correctly. Iterator like forEach, but it index is not from 0 to size-1 of collection. The every remove operations will creating a new collection that copy from updated old collection.
• T(n) = O(n), S(n) = O(m * n)
1. removeIf() method (JDK 8)
• Swap position of elements, set new size for collection, and set null for between new size to old size elements.
• T(n) = O(n), S(n) = O(1)
1. Stream API (JDK 8)
• Creating new collection. Traversing has no order.
• T(n) = O(n), S(n) = O(n) guess by “A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source.”

Recommend: removeIf() > stream() or parallelStream()> Collect objects set and removeAll() > Using iterator, or Collect indexes and remove one by one, or Collect objects set and remove one by one.

#### Ordered Collections

1. Sorted Collection Classes
• TreeSet
• TreeMap
1. Inserted order Collection Classes
1. Using Colletions sort() to sort Comparable elements

It uses merge sort. T(n) = O(log n)

• sort(List<T> list)
• sort(List<T> list, Comparator c)

Comparators

• Comparator.naturalOrder()
• Collections.reverseOrder()
• Collections.reverseOrder(Comparator c)

Summary: if you don’t need to keep collections always be ordered, you just use Collections sort() to get sorted collections.

#### Type Conversation

To ArrayList

Convert Set to ArrayList

Convert Wrapper Type Array to ArrayList

Convert Primitive Array to ArrayList

To Set

Convert ArrayList to Set

Convert Wrapper Type Array to Set

To Map

Convert Object Fields of List to Map

Array

## References

Variables and Types

Container