public class GuavaDemo {
/**
* 只讀數組
*/
@Test
public void guava1() {
// 創建定長不可修改的數組, 即"只讀"
// 方法一:
List<String> names = Arrays.asList("lee1", "lee2", "lee3");
names.add("lee4"); // UnsupportedOperationException
List<String> list = new ArrayList<>(names);
// 方法二:
List<String> cpList = Collections.unmodifiableList(list);
cpList.add("lee4"); // UnsupportedOperationException
// 方法三:
ImmutableList<String> iList = ImmutableList.of("lee5", "lee6", "lee7");
iList.add("lee8"); // UnsupportedOperationException
}
/**
* 過濾器
*/
@Test
public void guava2() {
List<String> names = Arrays.asList("lee1", "lee2", "lee3", "java", "json", "php", "c++");
Collections2.filter(names, (e) -> e.startsWith("j")).forEach(System.out::println);
}
/**
* 轉換
*/
@Test
public void guava3() {
Set<Long> DateSet = Sets.newHashSet(20190919L, 20190920L, 20190921L);
Collections2.transform(DateSet, (e) -> new SimpleDateFormat("yyyy-MM-dd").format(e))
.forEach(System.out::println); // output error!
}
/**
* 組合式函數
*/
@Test
public void guava4() {
List<String> names = Arrays.asList("lee1", "lee2", "lee3", "java", "json", "php", "c++");
Function<String, String> func1 = new Function<String, String>() {
@Override
public String apply(String s) {
return s.length() > 3 ? s.substring(0, 2) : s;
}
};
Function<String, String> func2 = new Function<String, String>() {
@Override
public String apply(String s) {
return s.toUpperCase();
}
};
Function<String, String> funcCps = Functions.compose(func1, func2);
Collections2.transform(names, funcCps).forEach(System.out::println);;
}
/**
* HashMultiset 無序可重複
*/
@Test
public void guava7() {
String s = "java c c++ c php golang java javascript golang golang";
String[] split = s.split(" ");
HashMultiset<String> set = HashMultiset.create();
for (String string : split) {
set.add(string);
}
Set<String> set2 = set.elementSet();
for (String string : set2) {
System.out.println(string + " cnt:" + set.count(string));
}
}
@Test
public void guava8() {
Map<String, String> map = new HashMap<>();
map.put("think in java", "aaa");
map.put("think in c++", "aaa");
map.put("java design partten", "bbb");
ArrayListMultimap<String, String> mmap = ArrayListMultimap.create();
Iterator<Entry<String, String>> entrySet = map.entrySet().iterator();
while (entrySet.hasNext()) {
Map.Entry<String, String> entry = entrySet.next();
mmap.put(entry.getValue(), entry.getKey());
}
for (String str : mmap.keySet()) {
List<String> values = mmap.get(str);
System.out.println(str + "=" + values);
}
}
}