1

Optional

create optional

Optional<T> opt = Optional.empty();
// create not null value
// if null throw exception .
Optional.of(xx);
// permit it null;
Optional.ofNullable().orElse();

some methods

  • get

description: if value is null that it will throw null exceptions. decrease use it.

// throw exception
Optional.ofNullable(null).get();
  • orElse

description: if value is null, it will call the method.

// it will return awqe
Optional.ofNullable(null).orElse("awqe");
  • orElseGet

description:'orElse plus', it receive a Function that it can create new value. if the cost of creating default value is huge, i suggest that you use it.

Optiona.ofNullable(null).orElseGet(Te::new);
  • orElseThrow

description: it receive exception, if it is null, and then throw it.

Optional.ofNullable(null).orElseThrow(RuntimeException::new);
  • ifPresent

description: if the value is not null that will called

Student s = new Student();
Optional.ofNullable(s).ifPresent(x -> {
    ... operator.
});
  • filter

description: if the value not null, it will called.

Student s = new Student();
Optional.ofNullable(s).filter(x -> true).ifPresent(...);

combiner options

person.flatMap(x -> car.map(v -> findxxx(p, v)));

Stream

sort

List l = new ArrayList<>();
l.add(9);
l.add(2);
l.add(3);
l.sort(Comparator.comparingInt(Integer::intValue).reversed());
l.sort(Comparator.comparingInt(Integer::intvalue).reversed());
public class Data {
    int score;
    String name;
    Getter and Setter ...
    public static void main(String[] args) {
        List l = new ArrayList<>();
        l.add(new Data(1,"1"));
        l.add(new Data(9,"9"));
        l.add(new Data(4,"4"));
             l.sort(Comparator.comparing(Data::getScore()).reversed().thenComparing(Data::getName));
    }
}

collector data (collect())

Reduce and summary

  • count
list.stream().count()
list.stream().collect(Collectors.couting);
  • max, min
list.stream().max(Comparator.comparingInt(Student::getScope));
list.stream().collect(Collectors.maxBy(Comparator.comparingInt(Student::getScope)));

list.stream().min(Comparator.comparingInt(Student::getScope));
list.stream().collect(Collectors.minBy(Comparator.comparoingInt(student::getScope)));
  • sum
list.stream().collect(Collectos.summingInt(Student::getScope));
// this is best
list.stream().mapToInt(Student::getScope).sum();
  • join string
list.stream().map(Student::getName).collect(Collectos.joining(","));
  • Collectors.reducing()

description: reducing receive three params

  • U identity: receive initial value. it is finaly return .
  • Function<? super T, ? extends U> mapper: convert operator.
  • BinaryOperator<U> op: reducing operator.

grouping

  • single grouping
list.stream().collect(Collectors.groupingBy(Student::getName));

list.stream().collect(Collectors.groupingBy(x -> {...}}));
  • multil grouping
Map<Integer, Map<String, Map<String, List<Student>>>> map = list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.groupingBy(Student::getScope)));

Map<Integer, Long> map = list.stream().collect(Collectos.groupingBy(Student::getName, Collectos.couting()));
 
Map<String, Optional<Student>> optionalMap = list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.maxBy(Comparator.comparingInt(Student::getScope))));
// remove option , this is best
 Map<String, Student> studentMap = list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.collectionAndThen(Collectors.maxBy(Comparators.comparingInt(Student::getScope), Optional::get))));
  • groupingBy with summingInt() collectors
list.stream().collect(Collectors.groupingBy(Student::getName, Collectors.summingInt(Student::getScope)));
  • groupingBy with mapping() collectors
list.stream().collect(Collectors.groupingBy(Student::getName, mapping(s -> {
    int scope = s.getScope();
    if (scope < 70 && scope > 60) {
        return "hege";
    } else if (scope < 80 && scope > 70) {
        return "hbc";
    } else if (scope > 80) {
        return "yx";
    } else {
        return "bjg";
    }
}, Collectors.toSet())));

... Collectors.toCollection(HashSet::new);

partitioningBy

  • simple use
Map<Boolean, List<Student>> map = list.stream().collect(partitionBy(x -> x.getScope > 60));
  • judge whether it is a prime number
IntStream.rangeClosed(2, 100).boxed().collect(Collectors.partitionBy(x -> {
    int closed = (int)Math.sqrt((double)x);
    return IntStream().rangeClosed(2, closed).anyMatch(v -> x % v == 0);
}));

Collectors interface

method sign:

 public interface Collector<T, A, R> {
        Supplier<A> supplier();
        BiConsumer<A, T> accumulator();
        Function<A, R> finisher();
        BinaryOperator<A> combiner();
        Set<Characteristics> characteristics();
}

params description:

  • T是流中要收集的项目的泛型。
  • A是累加器的类型,累加器是在收集过程中用于累积部分结果的对象。
  • R是收集操作得到的对象(通常但并不一定是集合)的类型。

methods descrption:

  • supplier: create new result
  • accumulator: add new item to result container
  • finisher: convert result that we need
  • combiner: conbiner result
  • characteristics: define collect behavior
  • picture of collectors logic

image.png

Date APIs

Date to LocalDateTime

  • method1
Date d = new Date();
LocalDateTime ldt = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
  • method2
Date d = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault());

Date to LocalDate

  • method1
Date d = new Date();
LocalDate ld = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().toLocalDate();
  • method2
Date d = new Date();
LocalDate ld = LocalDateTime.ofInstant(d.toInstant(), ZoneId.systemDefault()).toLocalDate();

LocalDateTime to Date

  • method1
LocalDateTime now = LocalDateTime.now();
Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

LocalDate to Date

  • method1
LocalDate now = LocalDate.now();
        Date from = Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant());

Handling different time zone

LocalDate now = LocalDate.now();
ZonedDateTime zonedDateTime = now.atStartOfDay(ZoneId.of("Europe/Rome"));
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zonedDateTime1 = now.atZone(ZoneId.of("Europe/Rome"));

calculate time difference

// 2019-10-19
LocalDate now = LocalDate.now();
LocalDate of = LocalDate.of(2017, 6, 12);
// -859;back minus font
ChronoUnit.DAYS.between(now, of);
// -2
ChronoUnit.YEAR.between(now, of);
// -28
ChronoUnit.MONTHS.between(now, of);
// UnsupportedTemporalTypeException
ChronoUnit.HOURS.between(now, of);
// 2019-10-19T17:27:34
LocalDateTime now = LocalDateTime.now();
LocalDateTime of = LocalDateTime.of(2016, 12, 12, 12, 12, 12);
// -24989
ChronoUnit.HOURS.between(now, of);
// -1499355
CHronoUnit.MINUTES.between(now, of);

format

LocalDateTime now = LocalDateTime.now();
// 2019-10-19
now.format(DateTimeFormatter.ISO_DATE);
// 20191019
now.format(DateTimeFormatter.BASIC_ISO_DATE);
// 19/33/19 17:10:17
now.format(DateTimeFormatter.ofPattern("yy/mm/dd HH:MM:ss"));
// 2019. 十月 19
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendText(ChronoField.YEAR)
                .appendLiteral(". ")
                .appendText(ChronoField.MONTH_OF_YEAR)
                .appendLiteral(" ")
                .appendText(ChronoField.DAY_OF_MONTH)
                .toFormatter(Locale.CHINA);
now.format(formatter)

parse

// 2019-10-19T01:12:12
LocalDateTime.parse("2019-10-19T01:12:12");
// 2019-10-19T17:33:17
LocalDateTime.parse("19/33/19 17:10:17", DateTimeFormatter.ofPattern("yy/mm/dd HH:MM:ss");
// 2019-10-19
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                .appendText(ChronoField.YEAR)
                .appendLiteral(". ")
                .appendText(ChronoField.MONTH_OF_YEAR)
                .appendLiteral(" ")
                .appendText(ChronoField.DAY_OF_MONTH)
                .toFormatter(Locale.CHINA);
LocalDate.parse("2019. 十月 19", formatter)

Temporal adjust

// 2019-10-19
LocalDate now = LocalDate.now();
// 2019-10-12
now.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
// 2019-10-19
now.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY))

TemporalAdjusters static methods

image.png

  • TemporalAdjusters.previous()
LocalDate now = LocalDate.now();
// consume today is saturday
LocalDate previous = now.with(TemporalAdjusters.previous(DayOfWeek.SATURDAY));
System.out.print(previous)
// it print 2019-10-12, it will minus days.
  • TemporalAdjusters.previousOrSame()
LocalDate now = LocalDate.now();
now = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.SATURDAY));
System.out.println(now)
// it print 2019-10-19, if day of week is satuday, it not minus days.
  • create new TemporalAdjust class
public class NextWorkingDay implements TemporalAdjuster {

    @Override
    public Temporal adjustInto(Temporal temporal) {
        int dayOfWeek = temporal.get(ChronoField.DAY_OF_WEEK);
        int plusDays = 2;
        if (dayOfWeek == DayOfWeek.SUNDAY.getValue()) {
            plusDays = 1;
        }

        return temporal.plus(plusDays, ChronoUnit.DAYS);
    }

    public static void main(String[] args) {
        LocalDate date = LocalDate.now().with(new NextWorkingDay());
        System.out.println(date);
    }
}
  • use TemporalAdjusts.ofDateAdjust() create TemporalAdjust
LocalDate date = LocalDate.now().with(TemporalAdjusters.ofDateAdjuster(temporal -> {
            int dayOfWeek = temporal.get(ChronoField.DAY_OF_WEEK);
            int plusDays = 2;
            if (dayOfWeek == DayOfWeek.SUNDAY.getValue()) {
                plusDays = 1;
            }
            return temporal.plus(plusDays, ChronoUnit.DAYS);
        }));

get year, month, day

  • method1
LocalDate now = LocalDate.now();
now.getYear();
now.getMonth().getValue();
now.getDayOfMonth();
  • method2
LocalDateTime now = LocalDateTime.now();
int year = now.get(ChronoField.YEAR);
int month = now.get(ChronoField.MONTH_OF_YEAR);
int days = now.get(ChronoField.DAY_OF_MONTH);

Duration

https://www.codercto.com/a/19...

Zone

ZoneId description

Replace java.util.TimeZone.

Create ZoneId

  • static method ZoneId.of()
// region/city
ZoneId zone = ZoneId.of("Europe/Rome")
  • create by TimeZone that old API
ZoneId zone = TimeZone.getDefault().toZoneId();

Create Date with Zone

  • add Zone for Date
// 2019-10-19T00:00+02:00[Europe/Rome]
LocalDate now = LocalDate.now();
ZonedDateTime zonedDateTime = now.atStartOfDay(ZoneId.of("Europe/Rome"));
        System.out.println(zonedDateTime);
// 2019-10-19T16:15:06.994+02:00[Europe/Rome]
LocalDateTime now1 = LocalDateTime.now();
ZonedDateTime zonedDateTime1 = now1.atZone(ZoneId.of("Europe/Rome"));
// 2019-10-19T10:15:06.994+02:00[Europe/Rome]
        Instant now2 = Instant.now();
        ZonedDateTime zonedDateTime2 = now2.atZone(ZoneId.of("Europe/Rome"));
  • LocalDate, LocalDateTime, ZoneId, ZoneDateTime differents

image.png


心无私天地宽
513 声望22 粉丝