EvictingQueue
这个是一个非阻塞的队列,当队列长度满了后,自动移除头元素,比如:
EvictingQueue<String> q = EvictingQueue.create(3);
q.add("one");
q.add("two");
q.add("three");
q.add("four");
// the head of the queue is evicted after adding the fourth element
fileTreeTraverser 文件遍历递归利器
这个方法可以快速遍历某个文件目录下的所有文件,比如:
FluentIterable<File> iterable = Files.fileTreeTraverser().breadthFirstTraversal(new File("/var/tmp"));
for (File f : iterable) {
System.out.println(f.getAbsolutePath());
}
其中f.getAbsolutePath()用的是jdk 7中的方法
Google Guava Splitter
Splitter niceCommaSplitter = Splitter.on(',') .omitEmptyString().trimResults();
niceCommaSplitter.split("one,, two, three"); //"one","two","three"
niceCommaSplitter.split(" four , five "); //"four","five"
Guava中Joiner的用法:
int[] numbers = { 1, 2, 3, 4, 5 };
String numbersAsStringDirectly = Ints.join(";", numbers);
Guava中Splitter的用法:
String testString = "foo , what,,,more,";
Iterable<String> split = Splitter.on(",").omitEmptyStrings().trimResults().split(testString);
set的交集, 并集, 差集的用法
HashSet setA = newHashSet(1, 2, 3, 4, 5);
HashSet setB = newHashSet(4, 5, 6, 7, 8);
SetView union = Sets.union(setA, setB);
System.out.println("union:");
for (Integer integer : union)
System.out.println(integer);
SetView difference = Sets.difference(setA, setB);
System.out.println("difference:");
for (Integer integer : difference)
System.out.println(integer);
SetView intersection = Sets.intersection(setA, setB);
System.out.println("intersection:");
for (Integer integer : intersection)
System.out.println(integer);
针对Map的用法:
MapDifference differenceMap = Maps.difference(mapA, mapB);
differenceMap.areEqual();
Map entriesDiffering = differenceMap.entriesDiffering();
Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
Map entriesInCommon = differenceMap.entriesInCommon();
验证与条件检查
public PostExample(final String title, final Date date, final String author) {
this.title = checkNotNull(title);
this.date = checkNotNull(date);
this.author = checkNotNull(author);
}
针对集合中只有一个元素的情况:
Iterables.getOnlyElement();
这个主要是用来替换Set.iterator.next()或 List.get(0), 而且在测试中使用非常方便, 如果出现0个或者2+则直接抛出异常
ImmutableList.copyOf的用法:
public Directions(Address from, Address to, List<Step> steps) {
this.from = from;
this.to = to;
this.steps = ImmutableList.of(steps);
}
equals和hashcode的用法:
public boolean equals(Object o) {
if (o instanceof Order) {
Order that = (Order)o;
return Objects.equal(address, that.address)
&& Objects.equal(targetArrivalDate, that.targetArrivalDate)
&& Objects.equal(lineItems, that.lineItems);
} else {
return false;
}
}
public int hashCode() {
return Objects.hashCode(address, targetArrivalDate, lineItems);
}