Guava



Guava

0 0


guava-slides

Slides for my Guava presentation on 2012-11-21 (made with reveal.js)

On Github csabapalfi / guava-slides

Guava

core Java libraries by

Joiner

Joiner

String joined = Joiner.on(":").join("A", "B", "C");
assertEquals("A:B:C", joined);

Splitter

",a,,b,".split(",") returns...?

Splitter

String toSplit = ": A::: B : C :::";

Iterable<String> parts = Splitter.on(":")
.omitEmptyStrings().trimResults().split(toSplit);

String backTogether = Joiner.on(":").join(parts);
assertEquals("A:B:C", backTogether);

Static factory methods

before

Set<Integer> someSet = new HashSet<Integer>();

after

Set<Integer> someSet = new Sets.newHashSet();

also

.newHashSet(E...elements);
.newHashSet(Iterable<? extends E> elements);
.newHashSet(Iterator<? extends E> elements);

Immutable Collections

  • stronger guarantee than unmodifiable
  • brand new standalone implementations
  • Immutable{List,Map,Set...}

#1: static sets

before

public static final Set<Integer> LUCKY_NUMBERS
= Collections.unmodifiableSet(
  new LinkedHashSet<Integer>(
    Arrays.asList(4, 8, 15, 16, 23, 42)));

after

public static final ImmutableSet<Integer> LUCKY_NUMBERS
  = ImmutableSet.of(4, 8, 15, 16, 23, 42);

#2: static maps

before

public static final Map<String, Integer> ENGLISH_TO_INT;
static {
  Map<String, Integer> map
    = new LinkedHashMap<String, Integer>();
  map.put("four", 4);
  map.put("forty-two", 42);
  ENGLISH_TO_INT = Collections.unmodifiableMap(map);
}

after

public static final ImmutableMap<String, Integer>
ENGLISH_TO_INT = ImmutableMap.builder()
  .put("four", 4)
  .put("forty-two", 42)
  .build();

#3: defensive copies

does it need to be mutable?

ImmutableSet.copyOf(someIterable);
ImmutableMap.copyOf(someMap);

caveats

  • null hostile
  • not deeply immutable

Multimaps

before

Map<Salesperson, List<Sale>> map
  = new HashMap<Salesperson, List<Sale>>();

public void makeSale(Salesperson salesPerson, Sale sale) {
  List<Sale> sales = map.get(salesPerson);
  if (sales == null) {
    sales = new ArrayList<Sale>();
    map.put(salesPerson, sales);
  }
  sales.add(sale);
}

Multimaps

after

Multimap<Salesperson, Sale> multimap
  = ArrayListMultimap.create();

public void makeSale(Salesperson salesPerson, Sale sale) {
  multimap.put(salesPerson, sale);
}

Multimaps

  • a Map except that keys don't have to be unique
  • {a=1, a=2, b=3}
  • get() returns a modifiable Collection view
  • use the asMap() returns {a=[1, 2], b=[3]}
  • plus keys(), keySet(), values(), entries()

Collection utilities

Sets

Set intersection(Set, Set)
Set<E> difference(Set<E>, Set<E>)
Set<E> union(Set<E>, Set<E>)

Collection utilities

Iterables

Iterable cycle(Iterable)
T getOnlyElement(Iterable<T>)
Iterable<T> reverse(List<T>)

Functional idioms

Function<F, T> {
  T apply(F input);
}

Predicate<T>{
  boolean apply(T input);
}

Iterable filter(Iterable, Predicate)
Iterable transform(Iterable, Function)

before

List<Integer> lengths = Lists.newLinkedList();
for (String string : strings) {
  if (string.startsWith("S")) {
    lengths.add(string.length());
  }
}

after

Function<String, Integer> lengthFunction =
    new Function<String, Integer>() {
  public Integer apply(String string) {
    return string.length();
  }
};

Predicate<String> startsWithS =
    new Predicate<String>() {
  public boolean apply(String string) {
    return string.startsWith("S")
  }
};

List<Integer> lengths = Lists.newLinkedList(
  Iterables.transform(
    Iterables.filter(strings, startsWithS), lengthFunction));

Ordering

  • Guava's enriched version of the Comparator class
  • Ordering.from(Comparator)
  • Provides: min(Iterable), max(Iterable), isIncreasing(Iterable), sortedCopy(Iterable), reverse()

Dealing with null

  • null is unpleasantly ambiguous
  • (e.g. Map.get)
  • sometimes used to indicate some sort of absence

Optional<T>

replacing a nullable T reference with a non-null value

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
Optional.of(T) accept non-null value, or fail fast on null. Optional.absent() return an absent Optional of some type. Optional.fromNullable(T) non-null is present and null is absent.

Ivy:

<dependency name="guava" org="com.google.guava" rev="13.0.1" />

Maven:

<dependency>
	<groupId>com.google.guava</groupId>
	<artifactId>guava</artifactId>
	<version>13.0.1</version>
</dependency>