使用Java的一些tips

2017-03-15  本文已影响44人  tenlee

不断更新中...

stream操作

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)));

其他

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();
        }
      }
}
<dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
 </dependency>
<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);
    }
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));
    }
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<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
上一篇 下一篇

猜你喜欢

热点阅读