Kotlin vs Java

ListOf
Java
final var map = Map.of(
    1, "One",
    2, "Two",
    3, "Three"
);
Kotlin
val numbers = listOf(1, 2, 3)

val map = mapOf(1 to "One",
                2 to "Two",
                3 to "Three")
Filter
Java
var filtered = numbers
    .stream()
    .filter(num -> num > 5)
    .collect(Collectors.toList())
Kotlin
val filtered = numbers.filter { it > 5 }
GroupBy
Java
final var groups = items.stream()
    .collect(
        Collectors.groupingBy(
            item -> (item % 2) == 0 ? "even" : "odd"
        )
);
Kotlin
val groups = numbers.groupBy {
    if (it % 2 == 0) "even" else "odd"
}
PartitionBy
Java
final var partitioned = numbers.stream()
        .collect(
            Collectors.partitioningBy(num -> num % 2 == 0)
        );

final var evens = partitioned.get(true);
final var odds = partitioned.get(false);
Kotlin
val (evens, odds) = numbers.partition { it % 2 == 0 }




SortBy
Java
final var users = getUsers();
users.sort(Comparator.comparing(user -> user.lastname));
Kotlin
val users = getUsers()
users.sortBy { it.lastname }
Fold
Java
private <T> Double calculateTotals(final Grid<T> grid) {
    return grid.getRows()
        .stream()
        .flatMap(e -> e.getColumns().stream())
        .collect(Collectors.groupingBy(Column::getTitle))
        .entrySet()
        .stream()
        .flatMap(e -> e.getValue().stream())
        .map(Column::getValue)
        .reduce(
            0.0,
            (accumulator, value) ->
                value instanceof Number
                    ? accumulator + ((Number) (value)).doubleValue()
                    : accumulator,
            Double::sum
        );

@Data // Lombok
class Grid<T> {
    private final List rows;
}

@Data // Lombok
class Row<T> {
    private final List columns;
}

@Data // Lombok
class Column<T> {
    private final String title;
    private final T value;
}
Kotlin
fun <T> calculateTotals(grid: Grid<T>) =
    grid.rows
        .flatMap(Row<T>::columns)
        .groupingBy(Column<T>::title)
        .fold(0.0) {
            accumulator,
            (_, value) ->
                accumulator +
                        when (value) {
                            is Number -> value.toDouble()
                            else -> 0.0
                        }
        }

data class Grid<T>(val rows: List)
data class Row<T>(val columns: List)
data class Column<T>(val title: String, val value: T)

// https://kotlinexpertise.com/kotlin-productivity/
AssociateBy
Java
final var map = currencies.stream()
    .collect(
        Collectors.toMap(
            Currency::getCode,
            Function.identity()
        )
    );
Kotlin
val map = currencies.associateBy { it.code }
Zip
Java
final var numbers = List.of(1, 2, 3);
final var names = List.of("Jack", "Michael", "Bob");
IntStream
    .range(0, Math.min(names.size(), ages.size()))
    .mapToObj(i -> names.get(i) + ":" + ages.get(i))
    .collect(Collectors.toList());
Kotlin
val pairs = listOf(1, 2, 3).zip(listOf("one", "two", "three")) // List>
Infix functions
Java
var list = List.of("a", "b", "c")
list.add("d")
list.remove("d")
Kotlin
val list = mutableListOf("a", "b", "c")
list += "d"
list -= "d"
CollectingAndThen
Java
final var topPaidEmployee = Map.of(
    "Alex", 250,
    "Boss", 999,
    "Chris", 400
).entrySet()
    .stream()
    .filter(employee -> !employee.getValue().equals("Boss"))
    .collect(
        Collectors.collectingAndThen(
            Collectors.maxBy(Comparator.comparing(Map.Entry::getValue)),
            employee -> {
                if (employee.isPresent() {
                    return employee.getKey(); 
                }
                throw new IllegalStateException("No employees");
            }
        )
    );
Kotlin
val topPaidEmployee = listOf("Alex" to 250, "Boss" to 999, "Chris" to 400)
    .filter { it.first != "Boss" }
    .maxBy { it.second }
    ?.run { first }
    ?: throw IllegalStateException("No employees")
For
Java
for (int i = 1; i < 11; i++) { }

for (int i = 1; i < 11; i += 2) { }

for (String item : collection) { }

for (var entry: map.entrySet()) { }
Kotlin
for (i in 1 until 11) { }

for (i in 1..10 step 2) {}

for (item in collection) {}
for ((index, item) in collection.withIndex()) {}

for ((key, value) in map) {}
Repeat
Java
for (int i = 0; i < 3; i++) {
    System.out.println("Hello")
}
Kotlin
repeat(3) {
    println("Hello")
}
Comparators
Java
var persons = List.of(
    new Person("Bob C.", 5), new Person("Alex G.", 10), new Person("Alex G.", 12)
);
persons.sort(
    Comparator
        .comparing(Person::getScore, Comparator.reverseOrder())
        .thenComparing((Person::getName), Comparator.naturalOrder())
);
// [(Alex G., 12), (Alex G., 10), (Bob C., 5)]

@Data // Lombok
class Person {
    private final String name;
    private final Integer score;
}

Kotlin
val personsSorted = listOf(
    Pair("Bob C.", 5), Pair("Alex G.", 10), Pair("Alex G.", 12)
).sortedWith(
    compareByDescending<Pair<String, Int>> { it.second }
        .thenBy { it. first }
)