?? Google Guava是什么東西渔工?首先要追溯到2007年的“Google Collections Library”項目锌钮,它提供對Java 集合操作的工具類。后來Guava被進化為Java程序員開發(fā)必備的工具引矩。Guava可以對字符串梁丘,集合,并發(fā)旺韭,I/O氛谜,反射進行操作。它提供的高質(zhì)量的 API 可以使你的JAVa代碼更加優(yōu)雅区端,更加簡潔值漫,讓你工作更加輕松愉悅。
guava類似Apache Commons工具集
1织盼、Guava地址
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0</version>
</dependency>
2杨何、基本工具包Base
基本工具包用很多酱塔,這次學(xué)到了Collections2
Collections2
Collections2中提供了幾個實用的靜態(tài)方法,今天試用一下晚吞。其中filter和transform有函數(shù)式的味道延旧。
- filter主要是提供了對集合的過濾功能。
@Test
public List<String> whenFilterWithCollections2_thenFiltered() {
List<String> names = Lists.newArrayList("John", "Jane", "Adam", "Tom");
Collection<String> result = Collections2.filter(names,
new Predicate<String>() {
@Override
public boolean apply(@Nullable String str) {
if (str == null) {
return false;
}
return true;
}
});
result.add("anna");
assertEquals(5, names.size());
return Lists.newArrayList(result);
}
這里注意的是槽地,Collections2.filter中迁沫,當(dāng)在上面的result中增加了元素后,會直接影響原來的names這個list的捌蚊,就是names中的集合元素是5了集畅。
com.google.common.base. Predicate : 根據(jù)輸入值得到 true 或者 false .
- transform():類型轉(zhuǎn)換
例:把Lis<Integer>中的Integer類型轉(zhuǎn)換為String , 并添加test作為后綴字符:
public class TransformDemo {
public static void main(String[] args) {
Set<Long> times= Sets.newHashSet();
times.add(91299990701L);
times.add(9320001010L);
times.add(9920170621L);
Collection<String> timeStrCol= Collections2.transform(times, new Function<Long, String>() {
@Nullable
@Override
public String apply(@Nullable Long input) {
return new SimpleDateFormat("yyyy-MM-dd").format(input);
}
});
System.out.println(timeStrCol);
}
}
需要說明的是每次調(diào)用返回都是新的對象,同時操作過程不是線程安全的缅糟。
多個Function組合:
public class TransformDemo {
public static void main(String[] args) {
List<String> list= Lists.newArrayList("abcde","good","happiness");
//確保容器中的字符串長度不超過5
Function<String,String> f1=new Function<String, String>() {
@Nullable
@Override
public String apply(@Nullable String input) {
return input.length()>5?input.substring(0,5):input;
}
};
//轉(zhuǎn)成大寫
Function<String,String> f2=new Function<String, String>() {
@Nullable
@Override
public String apply(@Nullable String input) {
return input.toUpperCase();
}
};
Function<String,String> function=Functions.compose(f1,f2);
Collection<String> results=Collections2.transform(list,function);
System.out.println(results);
}
}
Stopwatch
通常我們進行程序耗時計算和性能調(diào)試的時候挺智,需要統(tǒng)計某段代碼的運行時間,這個時候就是stopwatch的用武之處窗宦。
使用:
Stopwatch stopwatch = Stopwatch.createStarted();
//doSomething();
stopwatch.stop();
long millis = stopwatch.elapsed(MILLISECONDS);
log.info("time: " + stopwatch); // formatted string like "12.3 ms"