Contents
  1. 1. Basics
    1. 1.1. Variables and Types
      1. 1.1.1. Initialize variables
      2. 1.1.2. Initialize constants
      3. 1.1.3. Immutable Container
      4. 1.1.4. Enumeration Type vs Constants
      5. 1.1.5. Type Formatting
  2. 2. Core
  3. 3. Advanced
    1. 3.1. Container
      1. 3.1.1. Traversal
      2. 3.1.2. Remove elements from collection
      3. 3.1.3. Ordered Collections
      4. 3.1.4. Type Conversation
      5. 3.1.5. Print collections
      6. 3.1.6. Join
  4. 4. Utility Libraries
  5. 5. References

Basics

Variables and Types

Principles

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

Initialize variables

  • Primitive types
1
2
3
4
5
6
7
8
byte byteVal = 1;
short shortVal = 1;
int intVal = 1;
long longVal = 1L;
float floatVal = 1.0F;
double doubleVal = 1.0;
boolean booleanVal = true;
char charVal = 'a';
  • Strings and arrays
1
2
3
4
5
6
7
String str = "hello";
int[] array = {1, 2, 3};
int[] array2 = new int[]{1, 2, 3};
int[] array3 = new int[3];
array3[0] = 1;
array3[1] = 2;
array3[2] = 3;
1
2
// objects
Object object = new Object();
  • List
1
List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Set
1
2
3
4
5
6
7
8
9
10
11
12
// Using Another Collection Instance
Set<Integer> set = new HashSet<>(Arrays.asList(1, 2, 3));

// Using Anonymous Class
Set<Integer> set = new HashSet() {{
add(1);
add(2);
}};

// Using Stream Since Java 8
Set<String> set3 = Stream.of("a", "b", "c")
.collect(Collectors.toCollection(HashSet::new));
  • Maps
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Using Anonymous Class
Map<Integer, String> map = new HashMap<Integer, String>() {{
put(1, "one");
put(2, "two");
put(3, "three");
}};

// Using Stream Since Java 8
Map<String, Integer> map2 = Stream.of(new Object[][] {
{ "key1", 1 },
{ "key2", 2 },
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1]));

// Using a Stream of Map.Entry
Map<String, Integer> map3 = Stream.of(
new AbstractMap.SimpleEntry<>("key1", 1),
new AbstractMap.SimpleEntry<>("key2", 2))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Initialize constants

  • Primitive types
1
2
3
4
5
6
7
8
public static final byte byteVal = 1;
public static final short shortVal = 1;
public static final int intVal = 1;
public static final long longVal = 1L;
public static final float floatVal = 1.0F;
public static final double doubleVal = 1.0;
public static final boolean booleanVal = true;
public static final char charVal = 'a';
  • Strings and Arrays
1
public static final int[] MY_ARRAY = {1, 2, 3};
  • List
1
public static final List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3));
  • Set
1
2
3
4
5
public static final Set<Integer> SET = new HashSet();
static {
SET.add(1);
SET.add(2);
}
  • Map
1
2
3
4
5
6
public static final Map<Integer, String> MAP = new HashMap<Integer, String>();
static {
MAP.put(1, "one");
MAP.put(2, "two");
MAP.put(3, "three");
}

Immutable Container

  • Immutable List
1
2
3
4
5
// JDK 8 (Don't expose internal_list reference of unmodifiableList(List internale_list)). Arrays.asList() can't increase size, but it can modify its elements.
public static final List UNMODIFY_LIST = Collections.unmodifiableList(Arrays.asList(1, 2, 3));

// JDK 9 (Recommend, less space cost)
public static final List stringList = List.of("a", "b", "c");
  • Immutable Set
1
2
3
4
5
// JDK 8
public static final Set<String> stringSet = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));

// JDK 9 (Recommend)
public static final Set<String> stringSet2 = Set.of("a", "b", "c");
  • Immutable Map
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Immutable Map, JDK 8
public static final Map<Integer, String> UNMODIFY_MAP = Collections.unmodifiableMap(
new HashMap<Integer, String>()
{
{
put(1, "one");
put(2, "two");
put(3, "three");
};
});

// java 9, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map2 = Map.of(1, "one", 2, "two");

// java 10, return ImmutableCollections (Recommend)
public static final Map<Integer, String> my_map3 = Map.ofEntries(
entry(1, "One"),
entry(2, "two"),
entry(3, "three"));

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.
1
2
3
4
5
6
7
8
9
public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
1
2
3
4
5
6
7
public static final int MONDAY = 0;
public static final int TUESDAY = 1;
public static final int WEDNESDAY = 2;
public static final int THURSDAY = 3;
public static final int FRIDAY = 4;
public static final int SATURDAY = 5;
public static final int SUNDAY = 6;

Type Formatting

Double type formatting

1
2
Double value = 9.999;
String result = new DecimalFormat("#0.00").format(value);

Date formatting

1
2
Date date = new Date();
String result = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

Core

Advanced

Container

Traversal

Array Traversal

  • for (int i = 0; i < array.length; i++) {...}
  • Arrays.stream(array).xxx

List Traversal

  • for loop: for (int i = 0; i < list.size(); i++) {...}
  • enhanced for loop: for (Object o : list) {...}
  • iterator and listIterator
  • list.forEach(comsumer...)
  • list.stream().xxx

Map Traversal

  • for (String key : map.keySet()) {...}

  • for (Map.entry entry : map.entrySet()) {...}

  • Iterator

    1
    2
    3
    4
    5
    Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
    while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    System.out.println(entry.getKey() + ":" + entry.getValue());
    }
  • map.forEach(biComsumer...)

    1
    map.forEach((k, v) -> System.out.println((k + ":" + v)));
  • map.entrySet().stream()

forEach() vs stream()

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

Remove elements from collection

1
2
3
4
List<Book> books = new ArrayList<Book>();
books.add(new Book(new ISBN("0-201-63361-2")));
books.add(new Book(new ISBN("0-201-63361-3")));
books.add(new Book(new ISBN("0-201-63361-4")));
  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
3
4
5
6
7
8
ISBN isbn = new ISBN("0-201-63361-2");
List<Book> found = new ArrayList<Book>();
for(Book book : books){
if(book.getIsbn().equals(isbn)){
found.add(book);
}
}
books.removeAll(found);

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
2
3
4
5
6
ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
if(iter.next().getIsbn().equals(isbn)){
iter.remove();
}
}
  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
2
ISBN other = new ISBN("0-201-63361-2");
books.removeIf(b -> b.getIsbn().equals(other));
  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.”
1
2
3
4
ISBN other = new ISBN("0-201-63361-2");
List<Book> filtered = books.stream()
.filter(b -> b.getIsbn().equals(other))
.collect(Collectors.toList());

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
  • LinkedList
  • LinkedHashSet
  • LinkedHashMap
  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.

Compare object list using Collections.sort(objectList)

1
2
3
4
5
6
7
8
public class Animal implements Comparable<Animal> {
private String name;

@Override
public int compareTo(Animal o) {
return this.name.compareTo(o.name);
}
}

Type Conversation

To ArrayList

Convert Set to ArrayList

1
2
Set<String> set = new HashSet();
ArrayList<String> list = new ArrayList(set);
1
list.addAll(set);
1
2
// Java 8
List<String> list = set.stream().collect(Collectors.toList());
1
2
// Java 10
var list = List.copyOf(set);

Convert Wrapper Type Array to ArrayList

1
2
3
String[] array = new String[10];
Integer[] array2 = new Integer[10];
ArrayList<String> list = new ArrayList(Arrays.asList(array));

Convert Primitive Array to ArrayList

1
2
int[] input = new int[]{1,2,3,4};
List<Integer> output = Arrays.stream(input).boxed().collect(Collectors.toList());
1
2
int[] input = new int[]{1,2,3,4};
List<Integer> output = IntStream.of(input).boxed().collect(Collectors.toList());

To Set

Convert ArrayList to Set

1
2
ArrayList<String> list = new ArrayList();
Set<String> set = new HashSet(list);
1
set.addAll(aList);
1
2
// Java 8
Set<String> set = list.stream().collect(Collectors.toSet());
1
2
// Java 10
var set = Set.copyOf(list);

Convert Wrapper Type Array to Set

1
2
String[] array = new String[10];
Set<String> set = new HashSet(Arrays.asList(array));

To Map

Convert Object Fields of List to Map

1
2
3
4
List<SysUser> sysUserList = getSysUserIdNamesByIds(userIds);
Map<Long, String> idNameMap = sysUserList
.stream()
.collect(Collectors.toMap(SysUser::getId, SysUser::getName));

Array

1
2
int a[] = new int[]{1, 2, 3};
System.out.println(Arrays.toString(a));

Join

1
2
3
4
List<String> names = Arrays.asList("Tom", "Jack", "Lucy");
System.out.println(names.stream().map(Object::toString).collect(Collectors.joining(",")));
List<Integer> ids = Arrays.asList(1, 2, 3);
System.out.println(ids.stream().map(Object::toString).collect(Collectors.joining(",")));
1
2
List<String> names = Arrays.asList("Tom", "Jack", "Lucy");
System.out.println(String.join(",", names));

Utility Libraries

References

Variables and Types

Container

Contents
  1. 1. Basics
    1. 1.1. Variables and Types
      1. 1.1.1. Initialize variables
      2. 1.1.2. Initialize constants
      3. 1.1.3. Immutable Container
      4. 1.1.4. Enumeration Type vs Constants
      5. 1.1.5. Type Formatting
  2. 2. Core
  3. 3. Advanced
    1. 3.1. Container
      1. 3.1.1. Traversal
      2. 3.1.2. Remove elements from collection
      3. 3.1.3. Ordered Collections
      4. 3.1.4. Type Conversation
      5. 3.1.5. Print collections
      6. 3.1.6. Join
  4. 4. Utility Libraries
  5. 5. References