不斷更新中...
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);
- 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());
}