关闭

guava overview(very incomplete)

标签: methodsguava
99人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62572次
    • 积分:2215
    • 等级:
    • 排名:第17049名
    • 原创:139篇
    • 转载:29篇
    • 译文:24篇
    • 评论:7条
    文章分类
    最新评论