Guava 已经学习的代码整理
Guava 已经学习的代码整理
Guava 依赖:
compile group: 'com.google.guava', name: 'guava', version: '18.0'
以下是我自己在开发过程中使用到的谷歌 Guava 的一些例子,有些例子看起来确实没什么用,希望各位朋友们不吝赐教。
参考资料:
1、后悔当初的5年《Google Guava学习》专题
2、蓝学网 Guava 教程
3、
创建不可变集合
ImmutableSet<Integer> numbers = ImmutableSet.of(10,20,30,40,50);
numbers.forEach(System.out::println);
控制台显示:
连接器:集合转成字符串
Set<String> set = new HashSet<>();
set.add("one");
set.add("two");
set.add("three");
set.add("five");
set.add(null);
set.add("six");
// 把集合串成一个字符串,使用 "***" 连接,对于 null 的元素,使用 "no value" 来替代
String str = Joiner.on("***").useForNull("no value").join(set);
System.out.println(str);
控制台显示:
// 设置连接的方式和过滤的格式
Joiner joiner = Joiner.on(",").useForNull("这里是一个空格");
String result = joiner.join("hello",null,"world",null,"你好");
System.out.println(result);
控制台显示:
// 设置连接的方式和过滤的格式
Joiner joiner = Joiner.on("-").skipNulls();
String result = joiner.join("hello",null,"world",null,"你好");
System.out.println(result);
控制台显示:
拆分器:字符串分割
String str = " foo , , bar , queue , ";
// omit 省略空格
List<String> list = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(str);
list.forEach(System.out::println);
控制台显示:
Iterable<String> split = Splitter.on("|").split("android|java|ios| |hello");
Iterator<String> iterator = split.iterator();
StringBuilder sb = new StringBuilder();
while (iterator.hasNext()){
sb.append(iterator.next());
}
System.out.println(sb.toString());
控制台显示:
可以看到,没有跳过空格。
String str = "liwei:zhouguang:huzhenyu:wudi";
int size = Splitter.on(":").splitToList(str).size();
System.out.println(size);
控制台显示:
String str = "liwei:zhouguang:huzhenyu:wudi";
List<String> list = Splitter.on(":").splitToList(str);
list.forEach(System.out::println);
控制台显示:
创建不可变的 Map
ImmutableMap<String,String> map = ImmutableMap.<String,String>builder().
put("name","liwei").
put("age","24").
put("password","123456").
build();
for(Map.Entry<String,String> entry:map.entrySet()){
System.out.println(entry.getKey() + " - " + entry.getValue());
}
控制台显示:
计时(该功能比较常用)
// Stopwatch 旧的用法 Stopwatch stopwatch = new Stopwatch().start(); 已经被弃用
Stopwatch stopwatch = Stopwatch.createStarted();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println(elapsed);
时间单位有:
1、毫秒 TimeUnit.MILLISECONDS 1秒=10^3毫秒
2、微秒 TimeUnit.MICROSECONDS 1秒=10^6微秒
3、纳秒 TimeUnit.NANOSECONDS 1秒=10^9纳秒
下面的单元测试类比较了 Stopwatch.createUnstarted();
和 Stopwatch.createStarted();
的不同。
public class StopWatchDemo {
@Test
public void test01() {
Stopwatch stopwatch = Stopwatch.createUnstarted();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 表示开始计时
stopwatch.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopwatch.stop();
long spend = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("消耗了 => " + spend + " 毫秒");
}
@Test
public void test02() {
Stopwatch stopwatch = Stopwatch.createStarted();
// 如果不写 start() 就从 Stopwatch.createStarted(); 开始
// stopwatch.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopwatch.stop();
long spend = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("消耗了 => " + spend + "毫秒");
}
}
Objects 类的使用
public class Book {
private Integer id;
private String name;
private Date publishDate;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
public Book() {
}
public Book(Integer id, String name, Date publishDate) {
this.id = id;
this.name = name;
this.publishDate = publishDate;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", publishDate=" + publishDate +
'}';
}
}
Book book = new Book();
book.setId(1);
book.setName("《Spring In Action》");
book.setPublishDate(new Date());
String s = Objects.toString(book);
System.out.println(s);
String s1 = MoreObjects.toStringHelper(book)
.add("x", 1)
.add("name", book.getName())
.add("date",book.getPublishDate())
.toString();
System.out.println(s1);
控制台显示:
下面再给一个例子:
public class ToStringTest {
private Long userId;
private String name;
private String nickName;
private Gender gender;
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("name", "liwei")
.add("aaa", "bbb")
.add("userId", "1001").add("nickname", "李威威")
.add("gender", Gender.MAN).omitNullValues().toString();
}
public static void main(String[] args) {
System.out.println(new ToStringTest());
}
}
控制台显示:
boolean equals1 = Objects.equals("a", "a");
System.out.println(equals1); // true
boolean equals2 = Objects.equals(null, "a");
System.out.println(equals2); // false