guava overview(very incomplete)

guava overview(very incomplete)
Preconditions

Used to validate at the start of methods or constructors(and fail-fast if they aren’t valid);

class Car{
    private Engine engine;

    public Car(){}
    public Car(Engine engine){
        this.engine = Preconditions.checkNotNull(engine); //npe
    }

    public void drive(double speed){
        Preconditions.checkArgument(speed > 0.0, "speed (%s) must be positive", speed); //IAE
        Preconditions.checkState(engine.isRunning(), "engine must be running"); //ISE
    }
}

class Engine{

    public boolean isRunning(){
        return true;
    }
}
MoreObjects.toStringHelper()
@Override
    public String toString(){
        return MoreObjects.toStringHelper(this)
                .add("engine", engine)
                .omitNullValues()
                .toString();
    }
Stopwatch

prefer Stopwatch over System.nanoTime()

Stopwatch stopwatch = Stopwatch.createUnstarted();
stopwatch.start();
Thread.sleep(5 * 1000);
stopwatch.stop();
System.out.println(stopwatch.elapsed(TimeUnit.SECONDS));
String Splitting Quiz
private static Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
...
Iterable<String> array = SPLITTER.split("kurt,,,,,,Kevin,,");
Iterator<String> it = array.iterator();
while(it.hasNext()){
    System.out.println(it.next());
}
String joinning

Joiner concatenates strings using a delimiter
throws a NPE on null objects, unless:
* .skipNulls()
* .useForNull(String)

private static Joiner JOINER = Joiner.on(',').skipNulls();
...
String join = JOINER.join("Kevin", "", null, "ux");
CharMatcher

What’s a matching character?
* WHITESPACE, ASCII, ANY (many pre-defined sets)
* .is(‘x’), .isNot(‘_’), .oneOf(“aeiou”), .
inRange(‘a’, ‘z’)
* Or subclass CharMatcher, implement matches(char)

What to do with those matching characters?
* matchesAllOf, matchesAnyOf, matchesNoneOf
* indexIn, lastIndexIn, countIn
* removeFrom, retainFrom
* trimFrom, trimLeadingFrom, trimTrailingFrom
* collapseFrom, trimAndCollapseFrom,
replaceFrom

Optional\

An immutable wrapper that is either:
* present: contains a non-null reference
* absent: contains nothing
* Note that it never “contains null”

possible uses:
* return type (vs. null)
* “a T that must be present”
* “a T that might be absent”
* distinguish between
* “unknown” (for example, not present in a map)
* “known to have no value” (present in the map,
with value Optional.absent())
* wrap nullable references for storage in a collection
that does not support null
* Creating an Optional
* Optional.of(notNull);
* Optional.absent();
* Optional.fromNullable(maybeNull);
* Unwrapping an Optional
* mediaType.charset().get(); // maybe ISE
* mediaType.charset().or(Charsets.UTF_8);
* mediaType.charset().or(costlySupplier);
* mediaType.charset().orNull();
* Other useful methods:
* mediaType.charset().asSet(); // 0 or 1
* mediaType.charset().transform(stringFunc);

Functiion Programming
  • Function
Predicate<Car> activityCars = new Predicate<Car>(){
            @Override
            public boolean apply(Car input) {
                return input.isStarted();
            }

        };

ArrayList<Car> carList = new ArrayList<Car>();
carList.add(new Car());
carList.add(new Car());
carList.add(new Car());
FluentIterable.from(carList)
    .filter(activityCars) //Predicate
    .transform(Functions.toStringFunction()) //Function
    .limit(10)
    .toList();
FluentIterable API
  • chaining(return FluentIterable)
    • skip
    • limit
    • cycle
    • filter, transform
  • Querying(return boolean)
    • allMatch, anyMatch
    • contains, isEmpty
  • Converting
    • toList
    • toArray
  • Extracting
    • first, last, firstMatch(return optional)
    • get(return E)
Multiset
  • often called a bag
  • add multiple instances of a given element
  • counts how many occurrences exist
  • similar to a Map
BiMap
Table
Immutable Collections
  • offered for all collection types(including JDK ones)
  • inherently thread-safe
  • reduced memory footprint
  • slightly increased performance
  • similar to Collections.unmodifiableXXX, but …
    • performs a copy(not a view /wrapper)
    • more efficient compared to unmodifiable collections
    • type conveys immutability
Comparators

Who loves implementing comparators by hand?


这些功能还是让人眼前一亮的,但是文章中提到的很不全,慢慢了解,并在以后的用到的地方可以知道有这么个东西..

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值