import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.*;
import org.testng.annotations.Test;
import java.util.*;
import java.util.Objects;
/**
* @author: shouliang.wang
* @description:
* @date:created in 9:53 2017/12/8
* @modified by:
*/
public class GuavaTest {
@Test
public void StringsTest() {
//判断 String不为null,且不为空
String s2 = null;
// System.out.println(s2.isEmpty()); 报错
System.out.println(Strings.isNullOrEmpty(s2));
}
@Test
public void FilesTest() {
//复制文件
/*File from;
File`tos;
Files.copy(from,tos); //注意,只用了一行代码噢*/
}
@Test
public void ListsTest() {
//创建集合 可以省略后面繁琐的泛型定义
Map<String, Integer> map = Maps.newHashMap();
List<Object> list = Lists.newArrayList();
Set<Object> set = Sets.newHashSet();
}
@Test
public void OptionalTest1() {
//避免null
Optional<Integer> integer = null;
try {
//Optional.of 如果参数为null直接抛异常,会避免掉方法调用
integer = Optional.of(null);
//判断是否存在引用
if (integer.isPresent()) {
//调用
System.out.println(integer.get());
}
} catch (Exception e) {
//针对每个null做出提示
System.out.println("integer:为空,请核实");
e.printStackTrace();
}
}
@Test
public void OptionalTest2() {
//允许一个null参数
Optional<String> optional = Optional.fromNullable(null);
//如果Optional包含的T实例不为null,则返回true;若T实例为null,返回false
if (optional.isPresent()) {
//返回Optional包含的T实例,该T实例必须不为空;否则,对包含null的Optional实例调用get()会抛出一个IllegalStateException异常
System.out.println(optional.get());
} else {
// 若Optional实例中包含了传入的T的相同实例,返回Optional包含的该T实例,否则返回输入的T实例作为默认值
optional.or("我为空之后设置的");
}
//返回Optional实例中包含的非空T实例,如果Optional中包含的是空值,返回null,逆操作是fromNullable()
System.out.println(optional.orNull());
}
@Test
public void ObjectsTest() {
// 自带非空判断比较 避免对象为空时调用空指针异常
System.out.println(Objects.equals("a", null));
}
@Test
public void ImmutableTest() {
//创建不可变集合 优化性能
ImmutableList<Integer> list = ImmutableList.of(1, 2, 3, 4);
for (int i : list) {
System.out.println("list: " + i);
}
ImmutableMap<String, String> maps = ImmutableMap.of("key1", "value1", "key2", "value2");
UnmodifiableIterator<Map.Entry<String, String>> iterator = maps.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}
ImmutableSet<Integer> set = ImmutableSet.of(1, 2, 3, 4);
for (int s : set) {
System.out.println("set: " + s);
}
}
}
本文由 SAn 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2017/12/22 19:31