使用Java的一些tips

不断更新中...

stream操作

  • 使用stream把List<Object>转换为List<String>
List<String> names = persons.stream().map(Person::getName).collect(Collectors.toList());
  • 使用stream 把list 转 map
Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName,
                                              Function.identity()));
//如果key可能重复,这样做
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));  
// 分组统计
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语法 关闭在try-catch语句块中使用的资源.
    这些资源须实现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的实现为

 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,就优美很多

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());
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容