рдЬрд╛рд╡рд╛ рдЕрднреА рддрдХ рдорд░ рдирд╣реАрдВ рдЧрдпрд╛ рд╣реИ - рдФрд░ рд▓реЛрдЧ рдЗрд╕реЗ рд╕рдордЭрдиреЗ рд▓рдЧреЗ рд╣реИрдВред
рдЬрд╛рд╡рд╛ 8 рдЯреНрдпреВрдЯреЛрд░рд┐рдпрд▓ рдореЗрдВ рдЖрдкрдХрд╛ рд╕реНрд╡рд╛рдЧрдд рд╣реИред рдпрд╣ рд╕рд╛рдордЧреНрд░реА рдЖрдкрдХреЛ рднрд╛рд╖рд╛ рдХреА рд╕рднреА рдирдИ рд╡рд┐рд╢реЗрд╖рддрд╛рдУрдВ рдХреЗ рд╕рд╛рде рдХрджрдо рд╕реЗ рдХрджрдо рдорд┐рд▓рд╛рдПрдЧреАред рдЖрдк рд╕реАрдЦреЗрдВрдЧреЗ рдХрд┐ рдбрд┐рдлреЙрд▓реНрдЯ рдЗрдВрдЯрд░рдлрд╝реЗрд╕ рдореЗрдердб, рд▓реИрдореНрдмреНрдбрд╛ рдПрдХреНрд╕рдкреНрд░реЗрд╢рди, рдореЗрдердб рд░реЗрдлрд░реЗрдВрд╕ рдФрд░ рд░рд┐рдкреАрдЯреЗрдмрд▓ рдПрдиреЛрдЯреЗрд╢рди рдХрд╛ рдЙрдкрдпреЛрдЧ рдХреИрд╕реЗ рдХрд░реЗрдВред рдпрд╣ рд╕рдм рд╕рдВрдХреНрд╖рд┐рдкреНрдд рдФрд░ рд╕рд░рд▓ рдХреЛрдб рдЙрджрд╛рд╣рд░рдгреЛрдВ рдХреЗ рдмрд╛рдж рд╣реЛрдЧрд╛ред рд▓реЗрдЦ рдХреЗ рдЕрдВрдд рдореЗрдВ, рдЖрдк рдереНрд░реЗрдбреНрд╕, рдХрд╛рд░реНрдпрд╛рддреНрдордХ рдЗрдВрдЯрд░рдлреЗрд╕, рд╕рд╣рдпреЛрдЧреА рд╕рд░рдгрд┐рдпреЛрдВ рдХреЗ рд▓рд┐рдП рдПрдХреНрд╕рдЯреЗрдВрд╢рди, рд╕рд╛рде рд╣реА рддрд╛рд░реАрдЦреЛрдВ рдХреЗ рд╕рд╛рде рдХрд╛рдо рдХрд░рдиреЗ рдХреЗ рд▓рд┐рдП рдПрдкреАрдЖрдИ рдореЗрдВ рдкрд░рд┐рд╡рд░реНрддрди рдХреЗ рдмрд╛рд░реЗ рдореЗрдВ
рдПрдкреАрдЖрдИ рдореЗрдВ рдирд╡реАрдирддрдо рдкрд░рд┐рд╡рд░реНрддрдиреЛрдВ рд╕реЗ рдкрд░рд┐рдЪрд┐рдд рд╣реЛрдВрдЧреЗред
рдбрд┐рдлрд╝реЙрд▓реНрдЯ рдЗрдВрдЯрд░рдлрд╝реЗрд╕ рддрд░реАрдХреЗ
Java 8 ,
default
. , . :
interface Formula {
double calculate(int a);
default double sqrt(int a) {
return Math.sqrt(a);
}
}
calculate
Formula
sqrt
. , ,
calculate
.
sqrt
.
Formula formula = new Formula() {
@Override
public double calculate(int a) {
return sqrt(a * 100);
}
};
formula.calculate(100);
formula.sqrt(16);
formula
. : 6
sqrt(a * 100)
. , Java 8 .
-
: .
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
Collections.sort
, . .
Java 8 тАФ -, :
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
, . :
Collections.sort(names, (String a, String b) -> b.compareTo(a));
{}
return
. :
Collections.sort(names, (a, b) -> b.compareTo(a));
, . , -.
- Java? , .
. - . , , .
-, . , , ,
@FunctionalInterface
. , , .
:
@FunctionalInterface
interface Converter<F, T> {
T convert(F from);
}
Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
Integer converted = converter.convert("123");
System.out.println(converted);
,
@FunctionalInterface
.
, :
Converter<String, Integer> converter = Integer::valueOf;
Integer converted = converter.convert("123");
System.out.println(converted);
Java 8 .
::
. . :
class Something {
String startsWith(String s) {
return String.valueOf(s.charAt(0));
}
}
Something something = new Something();
Converter<String, String> converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted);
, . :
class Person {
String firstName;
String lastName;
Person() {}
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
, :
interface PersonFactory<P extends Person> {
P create(String firstName, String lastName);
}
:
PersonFactory<Person> personFactory = Person::new;
Person person = personFactory.create("Peter", "Parker");
Person::new
. ,
PersonFactory.create
.
- . ,
final
, .
final int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
stringConverter.convert(2);
,
num
final
. :
int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
stringConverter.convert(2);
num
.
:
int num = 1;
Converter<Integer, String> stringConverter = (from) -> String.valueOf(from + num);
num = 3;
num
- .
, -. .
class Lambda4 {
static int outerStaticNum;
int outerNum;
void testScopes() {
Converter<Integer, String> stringConverter1 = (from) -> {
outerNum = 23;
return String.valueOf(from);
};
Converter<Integer, String> stringConverter2 = (from) -> {
outerStaticNum = 72;
return String.valueOf(from);
};
}
}
?
Formula
sqrt
, , . -.
- . :
Formula formula = (a) -> sqrt( a * 100);
JDK 1.8 . , ,
Comparator
Runnable
.
@FunctionalInterface
.
Java 8 , . Google Guava. , , .
тАФ , , boolean. , (
and
,
or
,
negate
).
Predicate<String> predicate = (s) -> s.length() > 0;
predicate.test("foo");
predicate.negate().test("foo");
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();
. (
compose
,
andThen
).
Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
backToString.apply("123");
(suppliers) . , .
Supplier<Person> personSupplier = Person::new;
personSupplier.get();
(consumers) , .
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));
Java. Java 8 .
Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
comparator.compare(p1, p2);
comparator.reversed().compare(p1, p2);
(optionals) , NullPointerException. , , , .
тАФ , null. , , - , . , null, Java 8 .
Optional<String> optional = Optional.of("bam");
optional.isPresent();
optional.get();
optional.orElse("fallback");
optional.ifPresent((s) -> System.out.println(s.charAt(0)));
java.util.Stream
, . (intermediate) (terminal). , . . , ,
java.util.Collection
, ( ). , .
, . :
List<String> stringCollection = new ArrayList<>();
stringCollection.add("ddd2");
stringCollection.add("aaa2");
stringCollection.add("bbb1");
stringCollection.add("aaa1");
stringCollection.add("bbb3");
stringCollection.add("ccc");
stringCollection.add("bbb2");
stringCollection.add("ddd1");
Java 8 ,
Collection.stream()
Collection.parallelStream()
. .
Filter
Filter , .
, .. (,
forEach
) . ForEach , ( ) . ForEach
. , .
stringCollection
.stream()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println);
Sorted
Sorted
, . , :
stringCollection
.stream()
.sorted()
.filter((s) -> s.startsWith("a"))
.forEach(System.out::println);
,
sorted
.
stringCollection
:
System.out.println(stringCollection);
Map
map
. .
map
. ,
map
.
stringCollection
.stream()
.map(String::toUpperCase)
.sorted((a, b) -> b.compareTo(a))
.forEach(System.out::println);
Match
, , (match).
boolean.
boolean anyStartsWithA =
stringCollection
.stream()
.anyMatch((s) -> s.startsWith("a"));
System.out.println(anyStartsWithA);
boolean allStartsWithA =
stringCollection
.stream()
.allMatch((s) -> s.startsWith("a"));
System.out.println(allStartsWithA);
boolean noneStartsWithZ =
stringCollection
.stream()
.noneMatch((s) -> s.startsWith("z"));
System.out.println(noneStartsWithZ);
Count
Count
.
long
.
long startsWithB =
stringCollection
.stream()
.filter((s) -> s.startsWith("b"))
.count();
System.out.println(startsWithB);
Reduce
. .
Optional<String> reduced =
stringCollection
.stream()
.sorted()
.reduce((s1, s2) -> s1 + "#" + s2);
reduced.ifPresent(System.out::println);
, . , тАФ .
, , .
:
int max = 1000000;
List<String> values = new ArrayList<>(max);
for (int i = 0; i < max; i++) {
UUID uuid = UUID.randomUUID();
values.add(uuid.toString());
}
.
long t0 = System.nanoTime();
long count = values.stream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("sequential sort took: %d ms", millis));
long t0 = System.nanoTime();
long count = values.parallelStream().sorted().count();
System.out.println(count);
long t1 = System.nanoTime();
long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
System.out.println(String.format("parallel sort took: %d ms", millis));
, , . , ,
stream()
parallelStream()
.
, (maps) . , .
Map<Integer, String> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
map.putIfAbsent(i, "val" + i);
}
map.forEach((id, val) -> System.out.println(val));
:
putIfAbsent
null;
forEach
, .
:
map.computeIfPresent(3, (num, val) -> val + num);
map.get(3);
map.computeIfPresent(9, (num, val) -> null);
map.containsKey(9);
map.computeIfAbsent(23, num -> "val" + num);
map.containsKey(23);
map.computeIfAbsent(3, num -> "bam");
map.get(3);
, , :
map.remove(3, "val3");
map.get(3);
map.remove(3, "val33");
map.get(3);
:
map.getOrDefault(42, "not found");
? :
map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
map.get(9);
map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
map.get(9);
Merge
-. тАФ .
API
Java 8 API ,
java.time
. API
Joda-Time,
. API.
Clock
Clock
.
System.currentTimeMillis()
.
Instant
.
java.util.Date
.
Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);
ZoneId
. . , .
System.out.println(ZoneId.getAvailableZoneIds());
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
LocalTime
LocalTime
, , 10pm 17:30:15. , . , .
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1.isBefore(now2));
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);
System.out.println(minutesBetween);
LocalTime , , .
LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late);
DateTimeFormatter germanFormatter =
DateTimeFormatter
.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.GERMAN);
LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
System.out.println(leetTime);
LocalDate
LocalDate
, , 2014-03-11.
LocalDate
LocalTime
. , . , .
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);
LocalDate
:
DateTimeFormatter germanFormatter =
DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(xmas);
LocalDateTime
LocalDateTime
.
LocalDateTime
LocalTime
LocalDate
. -:
LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
System.out.println(dayOfWeek);
Month month = sylvester.getMonth();
System.out.println(month);
long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay);
Instant
.
Instant instant = sylvester
.atZone(ZoneId.systemDefault())
.toInstant();
Date legacyDate = Date.from(instant);
System.out.println(legacyDate);
- , . .
DateTimeFormatter formatter =
DateTimeFormatter
.ofPattern("MMM dd, yyyy - HH:mm");
LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
String string = formatter.format(parsed);
System.out.println(string);
java.text.NumberFormat
,
DateTimeFormatter
.
.
Java 8 . , , .
-, :
@interface Hints {
Hint[] value();
}
@Repeatable(Hints.class)
@interface Hint {
String value();
}
Java 8
@Repeatable
.
1: - ( )
@Hints({@Hint("hint1"), @Hint("hint2")})
class Person {}
2: ( )
@Hint("hint1")
@Hint("hint2")
class Person {}
2
@Hints
. .
Hint hint = Person.class.getAnnotation(Hint.class);
System.out.println(hint);
Hints hints1 = Person.class.getAnnotation(Hints.class);
System.out.println(hints1.value().length);
Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class);
System.out.println(hints2.length);
@Hints
Person
,
getAnnotation(Hints.class)
.
getAnnotationsByType
,
@Hint
.
, Java 8 :
@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
@interface MyAnnotation {}
Java 8 . JDK 1.8, ,
Arrays.parallelSort
,
StampedLock
,
CompletableFuture
.
GitHub.