40
Guava Ting Cheng

Android Guava

Embed Size (px)

Citation preview

Page 1: Android Guava

GuavaTing Cheng

Page 2: Android Guava
Page 3: Android Guava

Write less code

Page 4: Android Guava

Write cleaner code

Page 5: Android Guava

Write more readable code

Page 6: Android Guava

• “Null sucks” - Java Collections 群集框架及 JSR166

參與者之一, Doug Lea。

• “I call it my billion-dollar mistake” - 圖靈獎得主、快速排序發明者, Tony Hoare 在 QCon London 2009 主講《Null References: The Billion Dollar Mistake》場次時的一段話。

• 95% of collections weren’t supposed to have null

values. - google。

Page 7: Android Guava

com.google.guava:guava:15.0

Page 8: Android Guava

Avoid using nullBASIC

Page 9: Android Guava

……

private String name = null;

public String getName() {

return name;

}

……

名字是 怒爾?

null point excpetion

Page 10: Android Guava

Optional<T>

private String name = null;

public Optional<String> getName() {

if (name == null)

return Optional.absent();

else

return Optional.of(name);

}

//return “it empty”

getName().or(“it empty”)

//return false

getName().isPresent();

//return null

getName().orNull();

Page 11: Android Guava

String name =

Optional.fromNullable(getName()).or(“it empty”)

我有偶像包袱不想改 !

Page 12: Android Guava

PreconditionsBASIC

Page 13: Android Guava

……

private String name = null;

……

public void setName(String name) {

this.name = name;

}

if (name == null)

throw new NullPointerException();

if (name.length() > 10)

throw new IllegalArgumentException("Name invalid”);

Page 14: Android Guava

……

public void setName(String name){

this.name = name;

}

……

Preconditions.checkNotNull(name);

Preconditions.checkArgument(

name.length() < 10,

"Name invalid”

);

Page 15: Android Guava

Preconditions.checkArgument();

Preconditions.checkPositionIndex();

Preconditions.checkNotNull();

Preconditions.checkElementIndex();

Preconditions.checkState();

Page 16: Android Guava

ThrowablesBASIC

Page 17: Android Guava

• unchecked exceptions (runtime)

• checked exceptions

Page 18: Android Guava

……

try {

API.getInstance().getChannel()

} catch (xxx e) {

xxxx

} catch (xxx e) {

xxxx

} catch (APIException e) {

handle(e)

throw new APIException();

} catch (CookieException e) {

handle(e)

throw new CookieException();

} catch (LoginException e) {

handle(e)

throw new CookieException();

}

……

Page 19: Android Guava

Java 7

……

try {

API.getInstance().getChannel()

} catch (xxx e) {

xxxx

} catch (xxx e) {

xxxx

} catch (APIException |

CookieException |

LoginException e) {

handle(e)

throw e;

}

……

Page 20: Android Guava

try {

API.getInstance().getChannel();

} catch (xxxx e) {

xxxx

} catch (Throwable e) {

handle(e);

Throwables.propagateIfPossible(e,

APIException.class

);

Throwables.propagateIfPossible(e,

LoginException.class

);

Throwables.propagateIfPossible(e,

CookieException.class

);

throw Throwables.propagate(t);

}

Page 21: Android Guava

try { // case 1

xxxxx;

} catch (FileNotFoundException |

IOException e) {

e.printStackTrace();

}

try { //case 2

xxxxx;

} catch (FileNotFoundException e) {

} catch (IOException e) {

}

Page 22: Android Guava

Functional Idiom

Page 23: Android Guava

Javascript

var lengthFunction = function(str) {

return str.length;

}

console.log(lengthFunction("hello"));

Java

Function<String, Integer> lengthFunction = new

Function<String, Integer>() {

@Override

public Integer apply(String arg0) {

return arg0.length();

}

};

System.out.println(lengthFunction.apply("hello"));

Page 24: Android Guava

Collections

Page 25: Android Guava

List<String> words = Arrays.asList(

“one”, “two",

“three", “one”,

“three”

);

Set<String> wordSet = new HashSet<>(words);

// return [two, one, three]

Map<String, Integer> counts = new HashMap<>();

for(String word : words) {

Integer count = counts.get(word);

counts.put(word, count == null ? 1 : count + 1);

}

不重複

每個重複數

Page 26: Android Guava

多重集合(Multiset)

List<String> words = Arrays.asList(

"one", "two",

"three", “one",

"three");

330 中正路, 900 中正路100 承德路, 330 承德路

Map<Integer, List<Address>> bag = new HashMap<>();

Multimap

Multiset<String> wordBag =

HashMultiset.create(words);

// return [two, one x 2, three x 2]

Page 27: Android Guava

Multimap<Integer, Address> bag =

HashMultimap.create();

bag.put(330, 中正路);

bag.put(900, 中正路);

bag.put(100, 承德路);

bag.put(330, 承德路);

Key 和 Value 都可以重複,一般的 Map Key 不能重複會被蓋掉

Page 28: Android Guava

我要找 Map 裡面的 Value

for(Entry<Key, Value> userEntry: map.entrySet()) {

if(name.equals(userEntry.getValue())) {

return map.getKey();

}

}

(Bi-directional map)

BiMap<Key, Value> userBiMap =

HashBiMap.create(map)

userBiMap.inverse().get(value);

// return value

Key 和 Value 不能重複

Page 29: Android Guava

Ranges

Page 30: Android Guava

// 1 ~ 10

List<Integer> list = new ArrayList<>(20);

for(int i = 1; i <= 20; i++) {

list.add(i);

}

// a ~ z

List<Character> list = new ArrayList<>(26);

for(char c = 'a'; c <= 'z'; c++) {

list.add(c);

}

那如果 10 ~ +∞ ???

Page 31: Android Guava

Range.closed(1, 20)

(a..b) {x | a < x < b} open

[a..b] {x | a <= x <= b} closed

(a..b] {x | a < x <= b} openClosed

[a..b) {x | a <= x < b} closedOpen

(a..+∞) {x | x > a} greaterThan

[a..+∞) {x | x >= a} atLeast

(-∞..b) {x | x < b} lessThan

(-∞..b] {x | x <= b} atMost

(-∞..+∞) {x} all

Page 32: Android Guava

Range<Integer> range = Range.closed(1, 10);

range.contains(5);

range.contains(11);

System.out.println(range);

ContiguousSet<Integer> list =

ContiguousSet.create(

range,

DiscreteDomain.integers()

);

for (int i: list) {

System.out.println(i);

}

Page 33: Android Guava

Hashing

Page 34: Android Guava

怎麼產生 MD5?

<?php

$str = ‘miiicasa’;

echo md5($str);

?>

public static String md5Java(String message) {

String digest = null;

try {

MessageDigest md = MessageDigest.getInstance("MD5");

byte[] hash = md.digest(message.getBytes("UTF-8"));

String StringBuilder sb = new StringBuilder(2*hash.length);

for(byte b : hash){

sb.append(String.format("%02x", b&0xff));

}

digest = sb.toString();

} catch (UnsupportedEncodingException ex) {

throw Throwables.propagate(ex);

} catch (NoSuchAlgorithmException ex) {

throw Throwables.propagate(ex);

}

return digest;

}

Page 35: Android Guava

HashFunction hf = Hashing.md5();

hf.hashString("miiicasa", Charsets.UTF_8)

// more hash functions

Hashing.md5();

Hashing.murmur3_32();

Hashing.murmur3_128();

Hashing.sha1();

Hashing.sha256();

Hashing.sha512();

Page 36: Android Guava

Hash

Page 37: Android Guava

Bloom Filter

判斷一個元素有沒有在集合裡面?

資料量越來越大 O(n), O(longN)

Page 38: Android Guava

Q & A

Page 39: Android Guava

Demo

Page 40: Android Guava