Guava 已經學習的代碼整理

Guava 已經學習的代碼整理

Guava 依賴:html

compile group: 'com.google.guava', name: 'guava', version: '18.0'

如下是我本身在開發過程當中使用到的谷歌 Guava 的一些例子,有些例子看起來確實沒什麼用,但願各位朋友們不吝賜教。java

參考資料:
一、後悔當初的5年《Google Guava學習》專題
二、藍學網 Guava 教程
三、android

建立不可變集合

ImmutableSet<Integer> numbers = ImmutableSet.of(10,20,30,40,50);
numbers.forEach(System.out::println);

控制檯顯示:
ios

鏈接器:集合轉成字符串

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);

控制檯顯示:
app

// 設置鏈接的方式和過濾的格式
Joiner joiner = Joiner.on(",").useForNull("這裏是一個空格");
String result = joiner.join("hello",null,"world",null,"你好");
System.out.println(result);

控制檯顯示:
ide

// 設置鏈接的方式和過濾的格式
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);

控制檯顯示:
ui

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);

時間單位有:
一、毫秒 TimeUnit.MILLISECONDS 1秒=10^3毫秒
二、微秒 TimeUnit.MICROSECONDS 1秒=10^6微秒
三、納秒 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
相關文章
相關標籤/搜索