home

Collections

Arrays

Creating an Empty Array

int[] foo = new int[0];
int []bar = new int[0];
int baz[] = new int[0];

Creating an Array with Initial Values

int[] foo = {};
int[] bar = {1};
int[] baz = new int[]{1};

Mixing Arrays In to Multiple Variable Declarations

int[] foo, bar; // both arrays
int []foo, bar; // both arrays
int foo[], bar; // foo is an array bar is an int

Passing an Initalised Array to a Method

void arr(int[] arr) {};

arr(new int[]{}); // This is fine

// This will not compile
// arr({});

Arrays to Lists

String[] arr = {"foo", "bar"};
List<String> list = Arrays.asList(arr);
list.add("baz");  // throws UnsupportedOperationException

Queue

First In First Out Queue Example

Queue<Integer> iq = new LinkedList<>();
boolean itemadded;
itemadded = iq.offer(1);        // true
itemadded = iq.offer(2);        // true

System.out.println(iq.poll());  // 1
System.out.println(iq.poll());  // 2
System.out.println(iq.poll());  // null

First In Last Out Queue Example

Queue<Integer> iq = Collections.asLifoQueue(new LinkedList<Integer>());
boolean itemadded;
itemadded = iq.offer(1);        // true
itemadded = iq.offer(2);        // true

System.out.println(iq.poll());  // 2
System.out.println(iq.poll());  // 1
System.out.println(iq.poll());  // null

Iterable.forEach(Consumer)

Consumer<Integer> integerConsumer = i -> {}; // no-op consumer
Arrays.asList(1, 2).forEach(integerConsumer);

Heads Up! IntConsumer does not extend Consumer<Integer>

IntConsumer intConsumer = i -> {};
// This will not compile:
// Arrays.asList(1, 2).forEach(intConsumer);

Collection.removeIf(Predicate)

List<String> list = new ArrayList<>();
list.add("foo");
list.add("bar");
list.removeIf(s -> s.startsWith("f")); // foo is removed. list only contains [bar]

List.replaceAll(UnaryOperator)

List<String> list = new ArrayList<>();
list.add("foo");
list.add("bar");
list.replaceAll(s -> s.toUpperCase()); // [FOO, BAR]

List.sort(Comparator)

List<String> list = new ArrayList<>();
list.add("foobarbaz");
list.add("foobar");
list.add("foo");
list.sort((o1, o2) -> o1.length() - o2.length()); // [foo, foobar, foobarbaz]

Map.computeIfPresent(BiFunction)

static Map<String, Integer> nameAge = new HashMap<>();
static {
    nameAge.put("koray", 34);
    nameAge.put("deniz", 1);
}
nameAge.computeIfPresent("koray", (name, age) -> age + 10); // assigns a new value to the key
nameAge.computeIfPresent("deniz", (name, age) -> null);     // returning null removes the key from the map
System.out.println(nameAge);                                // {koray=44}

Map.putIfAbsent and Map.computeIfAbsent

Map<String, Integer> nameAge = new HashMap<>();

// putIfAbsent returns the existing value for the key
nameAge.putIfAbsent("kt", 34); // value inserted, null returned
nameAge.putIfAbsent("kt", 35); // value not inserted, 34 returned

nameAge.clear();

// computeIfAbsent returns the inserted value
nameAge.computeIfAbsent("kt", key -> 34); // value inserted, 34 returned
nameAge.computeIfAbsent("kt", key -> 35); // value not inserted, 34 returned

Concurrent Collections

BlockingQueue

Found in java.util.concurrent.BlockingQueue.

First In First Out Blocking Queue Example

BlockingQueue<String> bq = new LinkedBlockingQueue<>(2); // Initial capacity

Runnable letterCounter = () -> {
    try {
        Thread.sleep(10000);  // It takes 10 seconds to start counter to start its job
    } catch (InterruptedException e) {};
    while (true) {
        try {
            String toCount = bq.take();
            System.out.println("Finished counting letters in: " + toCount);
            System.out.println("Number of letters: " + toCount.length());
            Thread.sleep(10);  // counter needs to rest
        } catch (InterruptedException e) {}
    }
};

Runnable userInputReader = () -> {
    Scanner scanner = new Scanner(System.in);
    while (true) {
        System.out.println("Enter a sentence please:");
        String input = scanner.nextLine();
        if (!bq.offer(input)) {
            System.out.println("Blocked! We will add the sentence once queue is available!");
            try {
                bq.put(input);
                Thread.sleep(2000);  // Inform the user a little later
            } catch (InterruptedException e) {}
        }
        System.out.println("Your input: " + input + " is in queue!");
    }
};

new Thread(letterCounter).start();
new Thread(userInputReader).start();

Sample Output

Enter a sentence please:
koray
Your input: koray is in queue!
Enter a sentence please:
tugaaaaay
Your input: tugaaaaay is in queue!
Enter a sentence please:
lay lay lay lom
We are blocked! Please hold on! We will add the sentence once queue is available!
Finished counting letters in: koray
Number of letters: 5
Finished counting letters in: tugaaaaay
Number of letters: 9
Finished counting letters in: lay lay lay lom
Number of letters: 15
Your input: lay lay lay lom is in queue!
Enter a sentence please:

Notes

ConcurrentHashMap

ConcurrentHashMap Example

int emptyMapConcurrent(Map<Integer, Integer> integerMap) {
    // Add some data in the map first
    IntStream.rangeClosed(1, 100).boxed().forEach(i -> integerMap.put(i, i));
    
    // Runnable to remove all pairs from the map
    Runnable r = () -> integerMap.keySet().forEach(integerMap::remove);

    Thread i = new Thread(r);
    Thread j = new Thread(r);

    i.start();
    j.start();

    try {
        i.join();
        j.join();
    } catch (InterruptedException e) {}

    return integerMap.size();
}