---
# System prepended metadata

title: Cheat Sheet

---

# Cheat Sheet
## Collections

- List.of(...), Set.of(...), Map.of(...), List.copyOf(...) (immutable)
`List.of(1,2,3,4,5)`

- Stream::toList()
`Stream.of(1,2,3,4,5).map(i -> i * 2).toList()`

- `IntStream.iterate(1, i -> i < 100, i -> i + 1)`

- Predicate.not 
`Stream.of("foo", "", "bar").filter(not(String::isBlank))`

- Collectors.teeing(...)
`double mean = Stream.of(1, 2, 3, 4, 5).collect(Collectors.teeing(Collectors.summingDouble(i -> i),  Collectors.counting(), (sum, count) -> sum / count));`


## Optionals
- Optional.ofNullable(...).stream()
`List.of(Optional.of(1), Optional.empty(), Optional.of(2), Optional.of(3)).stream().flatMap(Optional::stream).sum() == 5`

- .ifPresentOrElse()
`Optional.of(4).ifPresentOrElse(value -> System.out.printf("Value is %d", value), () -> System.out.println("No value"))`

- .isEmpty()
`Optional.ofNullable(null).isEmpty()`

## Strings
- .isBlank()
- .strip()
- .lines()
`"foo\nbar\nbaz".lines().count() == 3`

- text block """
```
String json = """
        {
          "foo": "bar"
        }
        """;
```

## Other
- switch yield
```
int j = switch (day) {
    case MONDAY  -> 0;
    case TUESDAY -> 1;
    default      -> {
        int k = day.toString().length();
        int result = f(k);
        yield result;
    }
};
```

- records (immutable POJO)
```
Employee employee = new Employee(1, "John", "Doe");
Employee employeeCopy = new Employee(1, "John", "Doe");
System.out.println(employee.equals(employeeCopy));
System.out.println(employee.firstName());

public record Employee(int id, String firstName, String lastName) {}
```

- pattern matching (instanceof)
```
Object object = new Employee(1, "John", "Doe");
    if (object instanceof Employee e && e.firstName().equals("John")) {
        System.out.println("This is John!");
    }
```
