[ ](README.md)
# Java 8
+ [ , Java 8 JDK 8?](#----java-8--jdk-8)
+ [ __? -?](#---------)
+ [ -?](#-------)
+ [ -?](#-------)
+ [ ?](#----)
+ [ ?](#------)
+ [ `System.out::println`.](#--systemoutprintln)
+ [ ?](#---)
+ [ `Function`, `DoubleFunction`, `IntFunction` `LongFunction`?](#-----functiontr-doublefunctionr-intfunctionr--longfunctionr)
+ [ `UnaryOperator`, `DoubleUnaryOperator`, `IntUnaryOperator` `LongUnaryOperator`?](#-----unaryoperatort-doubleunaryoperator-intunaryoperator--longunaryoperator)
+ [ `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator` `LongBinaryOperator`?](#-----binaryoperatort-doublebinaryoperator-intbinaryoperator--longbinaryoperator)
+ [ `Predicate`, `DoublePredicate`, `IntPredicate` `LongPredicate`?](#-----predicatet-doublepredicate-intpredicate--longpredicate)
+ [ `Consumer`, `DoubleConsumer`, `IntConsumer` `LongConsumer`?](#-----consumert-doubleconsumer-intconsumer--longconsumer)
+ [ `Supplier`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier` `LongSupplier`?](#-----suppliert--booleansupplier-doublesupplier-intsupplier--longsupplier)
+ [ `BiConsumer`?](#-----biconsumertu)
+ [ `BiFunction`?](#-----bifunctiontur)
+ [ `BiPredicate`?](#-----bipredicatetu)
+ [ `_To_Function`?](#------tofunction)
+ [ `ToDoubleBiFunction`, `ToIntBiFunction` `ToLongBiFunction`?](#-----todoublebifunctiontu-tointbifunctiontu--tolongbifunctiontu)
+ [ `ToDoubleFunction`, `ToIntFunction` `ToLongFunction`?](#-----todoublefunctiont-tointfunctiont--tolongfunctiont)
+ [ `ObjDoubleConsumer`, `ObjIntConsumer` `ObjLongConsumer`?](#-----objdoubleconsumert-objintconsumert--objlongconsumert)
+ [ `StringJoiner`?](#--stringjoiner)
+ [ `default` ?](#--default--)
+ [ `default` ?](#--default-------)
+ [ `static` ?](#--static--)
+ [ `static` ?](#--static--)
+ [ `Optional`?](#--optional)
+ [ `Stream`?](#--stream)
+ [ ?](#----)
+ [ `Collection` `Stream`?](#----collection--stream)
+ [ `collect()` ?](#----collect--)
+ [ `forEach()` `forEachOrdered()`?](#------foreach--foreachordered)
+ [ `map()` `mapToInt()`, `mapToDouble()`, `mapToLong()`?](#------map--maptoint-maptodouble-maptolong)
+ [ `filter()` ?](#---filter--)
+ [ `limit()`?](#------limit)
+ [ `sorted()`?](#------sorted)
+ [ `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`?](#------flatmap-flatmaptoint-flatmaptodouble-flatmaptolong)
+ [ Java 8.](#-----java-8)
+ [ ?](#-------)
+ [ ?](#-------)
+ [ 10 , `forEach()`?](#----10----foreach)
+ [ `map()`?](#----------map)
+ [ `filter()`?](#----------filter)
+ [ 10 ?](#----10-----)
+ [ ?](#-----)
+ [ ?](#-----)
+ [ ?](#------)
+ [ ?](#-----)
+ [ (maps) Java 8?](#--------maps---java-8)
+ [ `LocalDateTime`?](#--localdatetime)
+ [ `ZonedDateTime`?](#--zoneddatetime)
+ [ Date Time API Java 8?](#------date-time-api--java-8)
+ [ 1 , 1 , 1 , 10 Date Time API?](#--1--1--1--10-------date-time-api)
+ [ Date Time API?](#-----date-time-api)
+ [ Date Time API?](#-------date-time-api)
+ [ Date Time API?](#---------date-time-api)
+ [ Date Time API?](#------------date-time-api)
+ [ ?](#---)
+ [ `Nashorn`?](#--nashorn)
+ [ `jjs`?](#--jjs)
+ [ Java 8 / ?](#----java-8---)
+ [ Base64 ?](#--base64---)
## , Java 8 JDK 8?
+ ;
+ -;
+ ;
+ ;
+ ;
+ ;
+ ;
+ _Stream API_ ;
+ ;
+ API ;
+ JavaScript _Nashorn_;
+ ;
+ API `Calendar` `Locale`;
+ _Unicode 6.2.0_;
+ _Base64_;
+ ;
+ `java.lang.String(byte[], *)` `java.lang.String.getBytes()`;
+ `AccessController.doPrivileged`, ;
+ _Password-based_ ;
+ _SSL/TLS Server Name Indication (NSI)_ _JSSE Server_;
+ (KeyStore);
+ _SHA-224_;
+ _JDBC - ODBC_;
+ _PermGen_, - ;
+ Java SE, , ;
+
+ `jjs` _JavaScript Nashorn_;
+ `java` _JavaFX_ ;
+ `jdeps` _.class_-.
[ ](#java-8)
## __? -?
____ , .
- _-_, `->`. - : , -, .
- , , . , .
```java
interface Operationable {
int calculate(int x, int y);
}
public static void main(String[] args) {
Operationable operation = (x, y) -> x + y;
int result = operation.calculate(10, 20);
System.out.println(result); //30
}
```
- , Java.
+ _ (deferred execution) -_- , , .
+ _ -_ :
```java
operation = (int x, int y) -> x + y;
// - :
(x, y) -> x + y;
// , , ,
() -> 30 + 20;
// , :
n -> n * n;
```
+ _ -_ - .
```java
interface Printable {
void print(String s);
}
public static void main(String[] args) {
Printable printer = s -> System.out.println(s);
printer.print("Hello, world");
}
```
+ _ -_ . - , , `if`, `switch`, .. - , `return`:
```java
Operationable operation = (int x, int y) -> {
if (y == 0) {
return 0;
}
else {
return x / y;
}
};
```
+ _ - _:
```java
interface Condition {
boolean isAppropriate(int n);
}
private static int sum(int[] numbers, Condition condition) {
int result = 0;
for (int i : numbers) {
if (condition.isAppropriate(i)) {
result += i;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(sum(new int[] {0, 1, 0, 3, 0, 5, 0, 7, 0, 9}, (n) -> n != 0));
}
```
[ ](#java-8)
## -?
- . :
+ (_effectively final_ - `final`) ;
+ ;
+ .
- .
[ ](#java-8)
## -?
```java
public static List sort(List list){
Collections.sort(list, (a, b) -> a.compareTo(b));
return list;
}
```
[ ](#java-8)
## ?
, , __method reference ( )__ . :
+ `_::__` ;
+ `_::_` ;
+ `_::new` .
, -, .
```java
private interface Measurable {
public int length(String string);
}
public static void main(String[] args) {
Measurable a = String::length;
System.out.println(a.length("abc"));
}
```
, -. , -, .
[ ](#java-8)
## ?
+ ;
+ ;
+ .
[ ](#java-8)
## `System.out::println`.
_instance method reference_: `println()` `out` `System`.
[ ](#java-8)
## ?
__ __ - , .
, `@FunctionalInterface`, `@Override`. .
`default` , `default` - .
[ ](#java-8)
## `Function`, `DoubleFunction`, `IntFunction` `LongFunction`?
__`Function`__ - , , `T` `R`.
(`compose`, `andThen`).
```java
Function toInteger = Integer::valueOf;
Function backToString = toInteger.andThen(String::valueOf);
backToString.apply("123"); // "123"
```
+ `DoubleFunction` - , `Double` `R`;
+ `IntFunction` - , `Integer` `R`;
+ `LongFunction` - , `Long` `R`.
[ ](#java-8)
## `UnaryOperator`, `DoubleUnaryOperator`, `IntUnaryOperator` `LongUnaryOperator`?
__`UnaryOperator` ( )__ `T`, `T`:
```java
UnaryOperator operator = x -> x * x;
System.out.println(operator.apply(5)); // 25
```
+ `DoubleUnaryOperator` - , `Double`;
+ `IntUnaryOperator` - , `Integer`;
+ `LongUnaryOperator` - , `Long`.
[ ](#java-8)
## `BinaryOperator`, `DoubleBinaryOperator`, `IntBinaryOperator` `LongBinaryOperator`?
__`BinaryOperator` ( )__ - , , `T` `T`.
```java
BinaryOperator operator = (a, b) -> a + b;
System.out.println(operator.apply(1, 2)); // 3
```
+ `DoubleBinaryOperator` - , `Double`;
+ `IntBinaryOperator` - , `Integer`;
+ `LongBinaryOperator` - , `Long`.
[ ](#java-8)
## `Predicate`, `DoublePredicate`, `IntPredicate` `LongPredicate`?
__`Predicate` ()__ - , , `T` `boolean`.
, (`and`, `or`, `negate`).
```java
Predicate predicate = (s) -> s.length() > 0;
predicate.test("foo"); // true
predicate.negate().test("foo"); // false
```
+ `DoublePredicate` - , `Double`;
+ `IntPredicate` - , `Integer`;
+ `LongPredicate` - , `Long`.
[ ](#java-8)
## `Consumer`, `DoubleConsumer`, `IntConsumer` `LongConsumer`?
__`Consumer` ()__ - , , `T`, .
```java
Consumer hello = (name) -> System.out.println("Hello, " + name);
hello.accept("world");
```
+ `DoubleConsumer` - , `Double`;
+ `IntConsumer` - , `Integer`;
+ `LongConsumer` - , `Long`.
[ ](#java-8)
## `Supplier`, `BooleanSupplier`, `DoubleSupplier`, `IntSupplier` `LongSupplier`?
__`Supplier` ()__ - , , , `T`;
```java
Supplier now = LocalDateTime::now;
now.get();
```
+ `DoubleSupplier` - , `Double`;
+ `IntSupplier` - , `Integer`;
+ `LongSupplier` - , `Long`.
[ ](#java-8)
## `BiConsumer`?
__`BiConsumer`__ , `T` `U` .
[ ](#java-8)
## `BiFunction`?
__`BiFunction`__ , `T` `U` `R`.
[ ](#java-8)
## `BiPredicate`?
__`BiPredicate`__ , `T` `U` `boolean`.
[ ](#java-8)
## `_To_Function`?
+ `DoubleToIntFunction` - `Double` `Integer`;
+ `DoubleToLongFunction` - `Double` `Long`;
+ `IntToDoubleFunction` - `Integer` `Double`;
+ `IntToLongFunction` - `Integer` `Long`;
+ `LongToDoubleFunction` - `Long` `Double`;
+ `LongToIntFunction` - `Long` `Integer`.
[ ](#java-8)
## `ToDoubleBiFunction`, `ToIntBiFunction` `ToLongBiFunction`?
+ `ToDoubleBiFunction` - `T` `U` `Double`;
+ `ToLongBiFunction` - `T` `U` `Long`;
+ `ToIntBiFunction` - `T` `U` `Integer`.
[ ](#java-8)
## `ToDoubleFunction`, `ToIntFunction` `ToLongFunction`?
+ `ToDoubleFunction` - `T` `Double`;
+ `ToLongFunction` - `T` `Long`;
+ `ToIntFunction` - `T` `Integer`.
[ ](#java-8)
## `ObjDoubleConsumer`, `ObjIntConsumer` `ObjLongConsumer`?
+ `ObjDoubleConsumer` - , `T` `Double`, ;
+ `ObjLongConsumer` - , `T` `Long`, ;
+ `ObjIntConsumer` - , `T` `Integer`, .
[ ](#java-8)
## `StringJoiner`?
`StringJoiner` , , :
```java
StringJoiner joiner = new StringJoiner(".", "prefix-", "-suffix");
for (String s : "Hello the brave world".split(" ")) {
joiner.add(s);
}
System.out.println(joiner); //prefix-Hello.the.brave.world-suffix
```
[ ](#java-8)
## `default` ?
Java 8 , `default`:
```java
interface Example {
int process(int a);
default void show() {
System.out.println("default show()");
}
}
```
+ , , , -, . .
+ , , . , , - .
+ `java.lang.Object`.
+ .
+ , .
+ , .
+ Java 8 -.
[ ](#java-8)
## `default` ?
`super` :
```java
interface Paper {
default void show() {
System.out.println("default show()");
}
}
class Licence implements Paper {
public void show() {
Paper.super.show();
}
}
```
[ ](#java-8)
## `static` ?
, , , .
+ ;
+ `java.lang.Object` ;
+ , , null, ..
[ ](#java-8)
## `static` ?
:
```java
interface Paper {
static void show() {
System.out.println("static show()");
}
}
class Licence {
public void showPaper() {
Paper.show();
}
}
```
[ ](#java-8)
## `Optional`?
`Optional` , `null`. `NullPointerException`, ..
, `if null/notNull` :
```java
Optional optional = Optional.of("hello");
optional.isPresent(); // true
optional.ifPresent(s -> System.out.println(s.length())); // 5
optional.get(); // "hello"
optional.orElse("ops..."); // "hello"
```
[ ](#java-8)
## `Stream`?
`java.util.Stream` , .
_ (intermediate)_ _ (terminal)_. , . .
. ( `Thread` `Runnable`, `start()`).
-, `java.util.Collection`.
(maps), , `HashMap`, .
, .
. - , .
`int`, `long` `double`: `IntStream`, `LongStream` `DoubleStream`. , , :
+ -, , `IntFunction` `IntPredicate` `Function` `Predicate`;
+ `sum()`, `average()`, `mapToObj()`.
[ ](#java-8)
## ?
1. :
```java
Stream fromCollection = Arrays.asList("x", "y", "z").stream();
```
2. :
```java
Stream fromValues = Stream.of("x", "y", "z");
```
3. :
```java
Stream fromArray = Arrays.stream(new String[]{"x", "y", "z"});
```
4. ( ):
```java
Stream fromFile = Files.lines(Paths.get("input.txt"));
```
5. :
```java
IntStream fromString = "0123456789".chars();
```
6. `Stream.builder()`:
```java
Stream fromBuilder = Stream.builder().add("z").add("y").add("z").build();
```
7. `Stream.iterate()` ():
```java
Stream fromIterate = Stream.iterate(1, n -> n + 1);
```
8. `Stream.generate()` ():
```java
Stream fromGenerate = Stream.generate(() -> "0");
```
[ ](#java-8)
## `Collection` `Stream`?
-, , .
: `Collection` - _ _. , `Set` , ,
`Stream`, _ _, , _ _ / ..
[ ](#java-8)
## `collect()` ?
`collect()` , - .
`collect()` `Collector`, : _supplier_ - , _accumulator_ - , _combiner_ - , _[finisher]_ - . Java 8 `Collectors` :
+ `toList()`, `toCollection()`, `toSet()` - , ;
+ `toConcurrentMap()`, `toMap()` - `Map`;
+ `averagingInt()`, `averagingDouble()`, `averagingLong()` - ;
+ `summingInt()`, `summingDouble()`, `summingLong()` - ;
+ `summarizingInt()`, `summarizingDouble()`, `summarizingLong()` - `SummaryStatistics` ;
+ `partitioningBy()` - `Map`;
+ `groupingBy()` - `Map`;
+ `mapping()` - `Collector`-.
`Collector.of()`:
```java
Collector toList = Collector.of(
ArrayList::new,
List::add,
(l1, l2) -> { l1.addAll(l2); return l1; }
);
```
[ ](#java-8)
## `forEach()` `forEachOrdered()`?
+ `forEach()` , ;
+ `forEachOrdered()` .
[ ](#java-8)
## `map()` `mapToInt()`, `mapToDouble()`, `mapToLong()`?
`map()` , .
`mapToInt()`, `mapToDouble()`, `mapToLong()` - `map()`, ( ):
```java
Stream
.of("12", "22", "4", "444", "123")
.mapToInt(Integer::parseInt)
.toArray(); //[12, 22, 4, 444, 123]
```
[ ](#java-8)
## `filter()` ?
`filter()` , , , .
[ ](#java-8)
## `limit()`?
`limit()` , .
[ ](#java-8)
## `sorted()`?
`sorted()` , , `Comparator`.
- `sorted()` .
[ ](#java-8)
## `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()`?
`flatMap()` map, . , , , . , .
```java
Stream
.of("H e l l o", "w o r l d !")
.flatMap((p) -> Arrays.stream(p.split(" ")))
.toArray(String[]::new);//["H", "e", "l", "l", "o", "w", "o", "r", "l", "d", "!"]
```
`flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()` - `flatMap()`, .
[ ](#java-8)
## Java 8.
. , . `ForkJoinPool` `ForkJoinPool.commonPool()` . , , . , , , , .
`parallelStream()` `Collection`.
, `Stream` `parallel()`. `isParallel()` .
, `parallel()` `sequential()` , . :
```java
collection
.stream()
.peek(...) //
.parallel()
.map(...) // ,
.sequential()
.reduce(...) //
```
, , . . `forEach()`, . , `forEachOrdered()`.
, :
+ - , , .
+ . , , . , .
+ , , . , `ArrayList` , . `LinkedList` - , /. .
+ , .
+ - (, ), c ForkJoinPool, JVM - , .. , , ;
+ , , `unordered()`:
```java
collection.parallelStream()
.sorted()
.unordered()
.collect(Collectors.toList());
```
[ ](#java-8)
## ?
+ `findFirst()` ;
+ `findAny()` ;
+ `collect()` ;
+ `count()` ;
+ `anyMatch()` `true`, ;
+ `noneMatch()` `true`, ;
+ `allMatch()` `true`, ;
+ `min()` , `Comparator`;
+ `max()` , `Comparator`;
+ `forEach()` ( );
+ `forEachOrdered()` ;
+ `toArray()` ;
+ `reduce()` .
:
+ `sum()` ;
+ `average()` .
[ ](#java-8)
## ?
+ `filter()` , , ;
+ `skip()` ;
+ `distinct()` ( `equals()`);
+ `map()` ;
+ `peek()` , ;
+ `limit()` ;
+ `sorted()` , `Comparator`;
+ `mapToInt()`, `mapToDouble()`, `mapToLong()` - `map()` ;
+ `flatMap()`, `flatMapToInt()`, `flatMapToDouble()`, `flatMapToLong()` - `map()`, .
`mapToObj()`, .
[ ](#java-8)
## 10 , `forEach()`?
```java
(new Random())
.ints()
.limit(10)
.forEach(System.out::println);
```
[ ](#java-8)
## `map()`?
```java
Stream
.of(1, 2, 3, 2, 1)
.map(s -> s * s)
.distinct()
.forEach(System.out::println);
```
[ ](#java-8)
## `filter()`?
```java
System.out.println(
Stream
.of("Hello", "", ", ", "world", "!")
.filter(String::isEmpty)
.count());
```
[ ](#java-8)
## 10 ?
```java
(new Random())
.ints()
.limit(10)
.sorted()
.forEach(System.out::println);
```
[ ](#java-8)
## ?
```java
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.max()
.getAsInt(); //55
```
[ ](#java-8)
## ?
```java
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.min()
.getAsInt(); //2
```
[ ](#java-8)
## ?
```java
Stream
.of(5, 3, 4, 55, 2)
.mapToInt()
.sum(); //69
```
[ ](#java-8)
## ?
```java
Stream
.of(5, 3, 4, 55, 2)
.mapToInt(a -> a)
.average()
.getAsDouble(); //13.8
```
[ ](#java-8)
## (maps) Java 8?
+ `putIfAbsent()` -, :
`map.putIfAbsent("a", "Aa");`
+ `forEach()` , :
`map.forEach((k, v) -> System.out.println(v));`
+ `compute()` ( ):
`map.compute("a", (k, v) -> String.valueOf(k).concat(v)); //["a", "aAa"]`
+ `computeIfPresent()` , ( ):
`map.computeIfPresent("a", (k, v) -> k.concat(v));`
+ `computeIfAbsent()` , , ( ):
`map.computeIfAbsent("a", k -> "A".concat(k)); //["a","Aa"]`
+ `getOrDefault()` , -:
`map.getOrDefault("a", "not found");`
+ `merge()` , , . , .
`map.merge("a", "z", (value, newValue) -> value.concat(newValue)); //["a","Aaz"]`
[ ](#java-8)
## `LocalDateTime`?
`LocalDateTime` `LocaleDate` `LocalTime`, ISO-8601 . . , plusMinutes, plusHours, isAfter, toSecondOfDay ..
[ ](#java-8)
## `ZonedDateTime`?
`java.time.ZonedDateTime` `java.util.Calendar`, ISO-8601. , .
[ ](#java-8)
## Date Time API Java 8?
```java
LocalDate.now();
```
[ ](#java-8)
## 1 , 1 , 1 , 10 Date Time API?
```java
LocalDate.now().plusWeeks(1);
LocalDate.now().plusMonths(1);
LocalDate.now().plusYears(1);
LocalDate.now().plus(1, ChronoUnit.DECADES);
```
[ ](#java-8)
## Date Time API?
```java
LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
```
[ ](#java-8)
## Date Time API?
```java
LocalDate
.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), 1)
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY))
.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
```
[ ](#java-8)
## Date Time API?
```java
new Date().toInstant();
```
[ ](#java-8)
## Date Time API?
```java
LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.systemDefault());
```
[ ](#java-8)
## ?
, - - `@Repeatable`:
```java
@interface Schedulers
{
Scheduler[] value();
}
@Repeatable(Schedulers.class)
@interface Scheduler
{
String birthday() default "Jan 8 1935";
}
```
[ ](#java-8)
## `Nashorn`?
__Nashorn__ - JavaScript, Java Oracle. JavaScript Java. _Rhino_, Mozilla Foundation, Nashorn 2 10 , - Java . Nashorn JavaScript Java, . Java JavaScript.
[ ](#java-8)
## `jjs`?
`jjs` , JavaScript .
[ ](#java-8)
## Java 8 / ?
`Base64` - , , base64 _RFC 4648_ _RFC 2045_.
Base64 6 :
`getEncoder()`/`getDecoder()` - / base64, _RFC 4648_;
`getUrlEncoder()`/`getUrlDecoder()` - URL-safe / base64, _RFC 4648_;
`getMimeEncoder()`/`getMimeDecoder()` - MIME /, _RFC 2045_.
[ ](#java-8)
## Base64 ?
```java
// Encode
String b64 = Base64.getEncoder().encodeToString("input".getBytes("utf-8")); //aW5wdXQ==
// Decode
new String(Base64.getDecoder().decode("aW5wdXQ=="), "utf-8"); //input
```
[ ](#java-8)
#
+ [ - Java 8](https://habrahabr.ru/post/216431/)
+ [ - Java 4. Java Stream API](https://habrahabr.ru/company/luxoft/blog/270383/)
+ [METANIT.COM](http://metanit.com/java/tutorial/9.1.php)
+ [javadevblog.com](http://javadevblog.com/interfejsy-v-java-8-staticheskie-metody-metody-po-umolchaniyu-funktsional-ny-e-interfejsy.html)
[ ](README.md)