JDK1.8中再用new Date()來創建日期會被同事鄙視的


JDK1.8中再用new Date()來創建日期會被同事鄙視的


一:簡介

JDK1.8中Map新增了一些方法,其中一部分方法是為了簡化代碼的,如forEach,另外一些方法是為了防止null,使操作代碼更加嚴謹。

二:Map

<code>public interface Map {
// 如果key存在,則忽略put操作
default V putIfAbsent(K key, V value) {
V v = get(key);
if (v == null) {
v = put(key, value);
}

return v;
}

// 循環
public void forEach(BiConsumer super K, ? super V> action){...}

// 如果存在則計算:先判斷key是否存在,如果key存在,將BiFunction計算的結果作為key的新值重新put進去
public V computeIfPresent(K key, BiFunction super K, ? super V, ? extends V> remappingFunction) {}

// 如果key不存在則將計算的結果put進去
public V computeIfAbsent(K key, Function super K, ? extends V> mappingFunction) {}

// 只有key-value同時滿足條件時才會刪除
public boolean remove(Object key, Object value){}

// 如果key不存在,則返回默認值

public V getOrDefault(Object key, V defaultValue) {}

// 合併:將BiFunction的結果作為key的新值
public V merge(K key, V value, BiFunction super V, ? super V, ? extends V> remappingFunction) {}
/<code>

三:示例

<code>@Test
public void putIfAbsent() {
Map<string> map = new HashMap<>();
map.putIfAbsent("key", "oldValue");
// 如果key存在,則忽略put操作
map.putIfAbsent("key", "newValue");
String value = map.get("key");
System.out.println(value);
}

@Test
public void forEach() {
Map<string> map = new HashMap<>();
map.putIfAbsent("key1", "value1");
map.putIfAbsent("key2", "value1");
map.putIfAbsent("key3", "value1");

map.forEach((key, value) -> System.out.println(key + ":" + value));
}

@Test
public void computeIfPresent() {
Map<string> map = new HashMap<>();
map.putIfAbsent("key1", "value1");

// 如果存在則計算:先判斷key是否存在,如果key存在,將BiFunction計算的結果作為key的新值重新put進去
map.computeIfPresent("key1", (key, value) -> key + "=" + value);
String value = map.get("key1");
System.out.println(value);

// 如果計算的結果為null,相當於從map中移除
map.computeIfPresent("key1", (k, v) -> null);
boolean contain = map.containsKey("key1");
System.out.println(contain);

}

@Test
public void computeIfAbsent() {
// 如果key不存在則將計算的結果put進去
Map<string> map = new HashMap<>();
map.computeIfAbsent("key2", v -> "value2");
boolean contain = map.containsKey("key2");
System.out.println(contain);
}

@Test
public void remove(){
Map<string> map = new HashMap<>();
map.putIfAbsent("key1", "value1");
boolean result = map.remove("key1", "value2");
System.out.println(result);
}

@Test
public void getOrDefault(){
Map<string> map = new HashMap<>();
String value = map.getOrDefault("key1", "default value");
System.out.println(value);
}

@Test
public void merge(){
Map<string> map = new HashMap<>();
map.put("key1", "value1");

map.merge("key1", "newValue", (value, newValue) -> value + "-" + newValue);
String value = map.get("key1");
// value1-newValue
System.out.println(value);
}
/<string>/<string>/<string>/<string>/<string>/<string>/<string>/<code>

Java 8 在包java.time下包含了一組全新的時間日期API。新的日期API和開源的Joda-Time庫差不多,但又不完全一樣。

Clock 時鐘

Clock類提供了訪問當前日期和時間的方法,Clock是時區敏感的,可以用來取代 System.currentTimeMillis() 來獲取當前的微秒數。某一個特定的時間點也可以使用Instant類來表示,Instant類也可以用來創建老的java.util.Date對象。

<code>@Test
public void clock(){
Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
Instant instant = clock.instant();
Date date = Date.from(instant);

System.out.println(millis);
System.out.println(date);
}
/<code>

Timezones 時區

在新API中時區使用ZoneId來表示。時區可以很方便的使用靜態方法of來獲取到。 時區定義了到UTS時間的時間差,在Instant時間點對象到本地日期對象之間轉換的時候是極其重要的。

<code>@Test
public void timezones(){
// 獲取所有可用的時區
Set<string> availableZoneIds = ZoneId.getAvailableZoneIds();
System.out.println(availableZoneIds);

// 獲取默認的時區 Asia/Shanghai
ZoneId zoneId = ZoneId.systemDefault();
System.out.println(zoneId);

// 獲取時區規則 ZoneRules[currentStandardOffset=+08:00]
ZoneRules rules = zoneId.getRules();
System.out.println(rules);
}
/<string>/<code>

LocalTime 本地時間

LocalTime 定義了一個沒有時區信息的時間,例如 晚上10點,或者 17:30:15。

<code>@Test 

public void localTime(){
ZoneId zoneId = ZoneId.systemDefault();
ZoneId zoneId2 = ZoneId.of("Etc/GMT+8");

// 獲取指定時區的當前時間
LocalTime now = LocalTime.now(zoneId);
LocalTime now2 = LocalTime.now(zoneId2);

// 判斷一個本地時間是否在另一個本地時間之前
boolean isBefore = now.isBefore(now2);

// 獲取兩個本地時間小時之差
long hours = ChronoUnit.HOURS.between(now, now2);
System.out.println(hours);

// 獲取兩個本地時間分鐘之差
long minutes = ChronoUnit.MINUTES.between(now, now2);
System.out.println(minutes);

LocalTime localTime = LocalTime.of(23, 59, 59);
System.out.println(localTime); // 23:59:59

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT).withLocale(Locale.GERMAN);
LocalTime local = LocalTime.parse("13:37", formatter);
System.out.println(local); // 13:37
}
/<code>

LocalDate 本地日期

LocalDate 表示了一個確切的日期,比如 2014-03-11。該對象值是不可變的,用起來和LocalTime基本一致。

<code>@Test
public void localDate(){
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);

System.out.println(today + "," + tomorrow + "," + yesterday);

LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);

DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);


DateTimeFormatter germanFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.GERMAN);
LocalDate localDate = LocalDate.parse("24.12.2014", germanFormatter);
System.out.println(localDate); // 2014-12-24
}
/<code>

LocalDateTime 本地日期時間

LocalDateTime 同時表示了時間和日期,相當於前兩節內容合併到一個對象上了。LocalDateTime和LocalTime還有LocalDate一樣,都是不可變的。LocalDateTime提供了一些能訪問具體字段的方法。

<code>@Test
public void localDateTime(){
LocalDateTime localDateTime = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println(dayOfWeek);

Month month = localDateTime.getMonth();
System.out.println(month);

long minuteOfDay = localDateTime.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay);

Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Date date = Date.from(instant);
System.out.println(date);

// DateTimeFormatter是不可變的,所以它是線程安全的
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime parsed = LocalDateTime.parse("2018-05-07 07:13:00", formatter);
String string = formatter.format(parsed);
System.out.println(string);
}
/<code>

本號將致力於發表實用的文章,歡迎關注Java實用技術,及時閱讀每天的優質文章。


分享到:


相關文章: