使用Java的一些tips

不斷更新中...

stream操作

  • 使用stream把List<Object>轉(zhuǎn)換為List<String>
List<String> names = persons.stream().map(Person::getName).collect(Collectors.toList());
  • 使用stream 把list 轉(zhuǎn) map
Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));
//如果key可能重復(fù),這樣做
Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity(), (v1, v2)->v1);
  • 分組
List<Item> items = Arrays.asList(  
               new Item("apple", 10),  
               new Item("banana", 20)
       );  
// 分組
Map<String, List<Item> nameGroup = items.stream().collect(  
               Collectors.groupingBy(Item::getName));  
// 分組統(tǒng)計
Map<String, Long> nameCount = Item.stream().collect(Collectors.groupingBy(Item::getName, Collectors.counting()));

Map<String, Integer> nameSum = items.stream().collect(Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getCount)));

其他

  • Java7以上使用 try-with-resources語法 關(guān)閉在try-catch語句塊中使用的資源.
    這些資源須實現(xiàn)java.lang.AutoCloseable接口
private static void printFileJava7() throws IOException {
    try(  FileInputStream input = new FileInputStream("file.txt");
          BufferedInputStream bufferedInput = new BufferedInputStream(input)
    ) {
        int data = bufferedInput.read();
        while(data != -1){
        System.out.print((char) data);
        data = bufferedInput.read();
        }
      }
}
  • 判斷 集合 為空 ,使用Apache CollectionUtils工具類,maven配置
<dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
 </dependency>
  • 返回空集合 Collections.emptyList(),Set為Collections.emptySet()
  • toString使用Apache ReflectionToStringBuilder.toString
    maven配置
<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
</dependency>

使用:

@Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this,
                ToStringStyle.MULTI_LINE_STYLE);
    }
  • 判斷兩個對象是否equal
    使用Objects.equals()方法,可以避免空指針異常
String str1 = null, str2 = "test";
str1.equals(str2); // 空指針異常
Objects.equals(str1, str2); // OK

Objects.equals的實現(xiàn)為

 public static boolean equals(Object a, Object b) {
        return (a == b) || (a != null && a.equals(b));
    }
  • 盡量多使用Optional
    一般情況下獲取某人汽車的名稱
if (person != null) {
    if (person.getCar() != null) {
       return person.getCar().getName();
    }
}

如果使用Optional,就優(yōu)美很多

Optional<Person> p = Optional.ofNullable(person);
return p.map(Person::getCar).map(Car::getName).orElse(null);

詳細了解Optional

  • Map遍歷
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容