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({});

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)

import java.util.*;

class Foo {
    void foo() {
        List<String> fooBar = new ArrayList<>();
        fooBar.add("foo");
        fooBar.add("bar");
        fooBar.removeIf(s -> s.startsWith("f")); // foo is removed. fooBar only contains [bar]
    }
}

List.replaceAll(UnaryOperator)

import java.util.*;

class Foo {
    void foo() {
        List<String> fooBar = new ArrayList<>();
        fooBar.add("foo");
        fooBar.add("bar");
        fooBar.replaceAll(s -> s.toUpperCase()); // [FOO, BAR]
    }
}

List.sort(Comparator)

import java.util.*;

class Foo {
    void foo() {
        List<String> fooBar = new ArrayList<>();
        fooBar.add("foobarbaz");
        fooBar.add("foobar");
        fooBar.add("foo");
        fooBar.sort((o1, o2) -> o1.length() - o2.length()); // [foo, foobar, foobarbaz]
    }
}

Map.computeIfPresent(BiFunction)

import java.util.Map;
import java.util.HashMap;


class Foo {

    static Map<String, Integer> nameAge = new HashMap<>();
    static {
        nameAge.put("koray", 34);
        nameAge.put("deniz", 1);        
    }

    public static void main(String[] args) {
        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.computeIfAbsent and Map.putIfAbsent

import java.util.Map;
import java.util.HashMap;

class App {
    public static void main(String[] args) {
        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
    }
}