Skip to content

Instantly share code, notes, and snippets.

@smanek
Created December 1, 2011 09:24
Show Gist options
  • Save smanek/1415292 to your computer and use it in GitHub Desktop.
Save smanek/1415292 to your computer and use it in GitHub Desktop.
public class GuavaExamples {
private static final Log log = LogFactory.getLog(GuavaExamples.class);
public static void main(String[] args) {
// The MapMaker/CacheBuilder is my very favorite part of Guava
// In its most basic form, you can use it to specify default values for keys
final Map<String, List<Integer>> grades = new MapMaker()
.makeComputingMap(new Function<String, List<Integer>>() {
public List<Integer> apply(@Nullable String s) {
return Lists.newLinkedList();
}
});
grades.get("John").add(90);
grades.get("Jacob").add(95);
// You can also use them to setup an LRU cache, where items get properly closed on eviction
// For example, let's say we want to write logs of user's actions to disk. We can make an excellent
// LRU cache that properly flushes log messages to disk in just a few lines of code.
// Make sure you evict all the keys when you shutdown your program though!
Cache<Long, BufferedWriter> perUserLogs = CacheBuilder.newBuilder()
.maximumSize(100)
.removalListener(new RemovalListener<Long, BufferedWriter>() {
public void onRemoval(RemovalNotification<Long, BufferedWriter> evictedItem) {
try {
evictedItem.getValue().close();
} catch (IOException e) {
log.error("Error closing the log writer for user " + evictedItem.getKey(), e);
}
}
})
.build(new CacheLoader<Long, BufferedWriter>() {
@Override
public BufferedWriter load(Long userId) throws Exception {
return new BufferedWriter(new FileWriter("/var/data/" + userId + ".log", true));
}
});
// The various small extensions to the standard Java Collections datastructures
// are useful too. I find myself using BiMap, MultiMap, and the Immutable* collections regularly
BiMap<String, Integer> wordsAndNumbers = HashBiMap.create();
wordsAndNumbers.put("one", 1);
wordsAndNumbers.put("two", 2);
wordsAndNumbers.get("one"); // => 1
wordsAndNumbers.inverse().get(2); // => "two"
// The Maps, Lists, and Sets utility classes have a number of useful methods you should explore
// some quick examples:
final List<Integer> numbers = Lists.newArrayList(1, 2, 3);
final List<Integer> doubled = Lists.transform(numbers, new Function<Integer, Integer>() {
public Integer apply(@Nullable Integer i) {
return i * 2;
}
});
final Set<Integer> somePrimes = Sets.newHashSet(2, 3, 5, 7, 11, 13, 17, 19);
final Set<Integer> someEvens = Sets.newHashSet(2, 4, 6, 8, 10, 12, 14, 16);
final Set<Integer> evenPrimes = Sets.intersection(someEvens, somePrimes);
final Set<Integer> oddPrimes = Sets.difference(somePrimes, someEvens);
// This is a little less cool now that Java 7 has the diamond operator
// (http://docs.oracle.com/javase/tutorial/java/generics/gentypeinference.html#type-inference-instantiation)
// But hardly a day goes by when I don't use the static Collection factory methods for Maps/Lists/etc
final Map<String, List<ShortCourseNameJson.Student>> studentMap = Maps.newHashMap();
// Guava also provides a number of string manipulation utilities, like the Joiner, Splitter, and charmatcher.
final String[] vals = {"FirstVal", null, "Second", "evenmore"};
final String joinedVals = Joiner.on(", ").skipNulls().join(vals);
// This is how I'd have to join strings without the Joiner:
//
// final StringBuilder joinedValsBuilders = new StringBuilder();
// boolean first = true;
// for (String val : vals) {
// if (val != null) {
// if (first) {
// first = false;
// } else {
// joinedValsBuilders.append(", ");
// }
//
// joinedValsBuilders.append(val);
// }
// }
// final String joinedVals = joinedValsBuilders.toString();
final String commaSeparatedValues = "Hello, World, , And Other Stuff";
final Iterable<String> splits = Splitter.on(",").omitEmptyStrings().trimResults().split(commaSeparatedValues);
// And without a 'splitter':
// final String[] rawSplits = commaSeparatedValues.split(",");
// final List<String> trimmedSplits = new LinkedList<String>();
// for (String s : rawSplits) {
// final String trimmed = s.trim();
// if (trimmed.length() > 0) {
// trimmedSplits.add(trimmed);
// }
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment