87.md 21.2 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6
# Google Guava 简介

原文:http://zetcode.com/articles/guava/

本教程是 Guava 库的简介。 我们看一下 Guava 库的一些有趣的功能。

W
wizardforcel 已提交
7
## Guava 
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9
Google Guava 是 Java 通用库的开源集合,主要由 Google 工程师开发。 Google 有许多 Java 项目。 Guava 是解决那些项目中遇到的许多常见问题的解决方案,其中包括集合,数学,函数习语,输入&输出和字符串等领域。
W
wizardforcel 已提交
10 11 12

Guava 的某些功能已经包含在 JDK 中。 例如`String.join()`方法已引入 JDK 8。

W
wizardforcel 已提交
13
## Guava  Maven 依赖
W
wizardforcel 已提交
14 15 16

在我们的示例中,我们使用以下 Maven 依赖关系。

W
wizardforcel 已提交
17
```java
W
wizardforcel 已提交
18 19 20 21 22 23 24 25
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>19.0</version>
</dependency>

```

W
wizardforcel 已提交
26
## Guava 初始化集合
W
wizardforcel 已提交
27

W
wizardforcel 已提交
28
Guava 允许在一行中初始化集合。 JDK 8 不支持集合字面值。
W
wizardforcel 已提交
29 30 31

`InitializeCollectionEx.java`

W
wizardforcel 已提交
32
```java
W
wizardforcel 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
package com.zetcode.initializecollectionex;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;

public class InitializeCollectionEx {

    public static void main(String[] args) {

        Map items = ImmutableMap.of("coin", 3, "glass", 4, "pencil", 1);

        items.entrySet()
                .stream()
                .forEach(System.out::println);

        List<String> fruits = Lists.newArrayList("orange", "banana", "kiwi", 
                "mandarin", "date", "quince");

        for (String fruit: fruits) {
            System.out.println(fruit);
        }
    }
}

```

W
wizardforcel 已提交
61
在示例中,我们使用 Guava 的工厂方法创建映射和列表。
W
wizardforcel 已提交
62

W
wizardforcel 已提交
63
```java
W
wizardforcel 已提交
64 65 66 67 68 69
Map items = ImmutableMap.of("coin", 3, "glass", 4, "pencil", 1);

```

使用`ImmutableMap.of()`方法创建一个新映射。

W
wizardforcel 已提交
70
```java
W
wizardforcel 已提交
71 72 73 74 75 76 77
List<String> fruits = Lists.newArrayList("orange", "banana", "kiwi", 
        "mandarin", "date", "quince");

```

使用`Lists.newArrayList()`方法创建一个新的字符串列表。

W
wizardforcel 已提交
78
```java
W
wizardforcel 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92
coin=3
glass=4
pencil=1
orange
banana
kiwi
mandarin
date
quince

```

这是示例的输出。

W
wizardforcel 已提交
93
## Guava `MoreObjects.toStringHelper()`
W
wizardforcel 已提交
94 95 96 97 98

`MoreObjects.toStringHelper()`有助于轻松创建具有一致格式的`toString()`方法,它使我们可以控制所包含的字段。

`Car.java`

W
wizardforcel 已提交
99
```java
W
wizardforcel 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
package com.zetcode.tostringex.beans;

import com.google.common.base.MoreObjects;

public class Car {

    private long Id;
    private String Name;
    private int Price;

    public Car(long Id, String Name, int Price) {
        this.Id = Id;
        this.Name = Name;
        this.Price = Price;
    }

    public long getId() {
        return Id;
    }

    public void setId(long Id) {
        this.Id = Id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public int getPrice() {
        return Price;
    }

    public void setPrice(int Price) {
        this.Price = Price;
    }

   @Override
    public String toString() {
        return MoreObjects.toStringHelper(Car.class)
            .add("id", Id)
            .add("name", Name)
            .add("price", Price)
            .toString();
    }    
}

```

这是一个`Car` bean。 它包含`toString()`方法,该方法给出对象的字符串表示形式。

W
wizardforcel 已提交
154
```java
W
wizardforcel 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
@Override
public String toString() {
    return MoreObjects.toStringHelper(Car.class)
        .add("id", Id)
        .add("name", Name)
        .add("price", Price)
        .toString();
}  

```

除了使用字符串之外,我们还提供了`MoreObjects.toStringHelper()`方法更简洁的解决方案。

`ToStringEx.java`

W
wizardforcel 已提交
170
```java
W
wizardforcel 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
package com.zetcode.tostringex;

import com.zetcode.tostringex.beans.Car;

public class ToStringEx {

    public static void main(String[] args) {

        Car car1 = new Car(1, "Audi", 52642);
        Car car2 = new Car(2, "Mercedes", 57127);
        Car car3 = new Car(3, "Skoda", 9000);

        System.out.println(car1);
        System.out.println(car2);
        System.out.println(car3);
    }
}

```

我们创建三个汽车对象,并将它们传递给`System.out.println()`方法。 该方法调用对象的`toString()`方法。

W
wizardforcel 已提交
193
```java
W
wizardforcel 已提交
194 195 196 197 198 199 200 201
Car{id=1, name=Audi, price=52642}
Car{id=2, name=Mercedes, price=57127}
Car{id=3, name=Skoda, price=9000}

```

This is the output of the example.

W
wizardforcel 已提交
202
## Guava `FluentIterable`
W
wizardforcel 已提交
203 204 205 206 207

`FluentIterable`提供了一个强大而简单的 API,可以流畅地操作`Iterable`实例。 它允许我们以各种方式过滤和转换集合。

`Car.java`

W
wizardforcel 已提交
208
```java
W
wizardforcel 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
package com.zetcode.fluentiterable.beans;

import com.google.common.base.MoreObjects;

public class Car {

    private long Id;
    private String Name;
    private int Price;

    public Car(long Id, String Name, int Price) {
        this.Id = Id;
        this.Name = Name;
        this.Price = Price;
    }

    public long getId() {
        return Id;
    }

    public void setId(long Id) {
        this.Id = Id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }

    public int getPrice() {
        return Price;
    }

    public void setPrice(int Price) {
        this.Price = Price;
    }

   @Override
    public String toString() {
        return MoreObjects.toStringHelper(Car.class)
            .add("id", Id)
            .add("name", Name)
            .add("price", Price)
            .toString();
    }    
}

```

在此示例中,我们有一个`Car` bean。

`FluentIterableEx.java`

W
wizardforcel 已提交
265
```java
W
wizardforcel 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
package com.zetcode.fluentiterable;

import com.google.common.base.Functions;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.zetcode.fluentiterable.beans.Car;
import java.util.List;

public class FluentIterableEx {

    public static void main(String[] args) {

        List<Car> cars = Lists.newArrayList(new Car(1, "Audi", 52642),
                new Car(2, "Mercedes", 57127), new Car(3, "Skoda", 9000),
                new Car(4, "Volvo", 29000));

        Predicate<Car> byPrice = car -> car.getPrice() <= 30000;

        List<String> results = FluentIterable.from(cars)
                .filter(byPrice)
                .transform(Functions.toStringFunction())
                .toList();

        System.out.println(results);
    }
}

```

W
wizardforcel 已提交
296
在代码示例中,我们有一个汽车对象列表。 我们通过将列表减少为仅适用于价格低于 30000 辆的汽车来对其进行改造。
W
wizardforcel 已提交
297

W
wizardforcel 已提交
298
```java
W
wizardforcel 已提交
299 300 301 302 303 304
List<Car> cars = Lists.newArrayList(new Car(1, "Audi", 52642),
        new Car(2, "Mercedes", 57127), new Car(3, "Skoda", 9000),
        new Car(4, "Volvo", 29000));

```

W
wizardforcel 已提交
305
创建`Car`对象的列表。 JDK 中没有集合字面值。 我们使用 Guava 中的`Lists.newArrayList()`初始化列表。
W
wizardforcel 已提交
306

W
wizardforcel 已提交
307
```java
W
wizardforcel 已提交
308 309 310 311 312 313
Predicate<Car> byPrice = car -> car.getPrice() <= 30000;

```

创建了`Predicate`。 谓词是一个返回布尔值的函数。 该谓词确定汽车是否比 30000 便宜。

W
wizardforcel 已提交
314
```java
W
wizardforcel 已提交
315 316 317 318 319 320 321 322 323
List<String> results = FluentIterable.from(cars)
        .filter(byPrice)
        .transform(Functions.toStringFunction())
        .toList();

```

`cars`集合创建一个`FluentIterable`。 谓词功能应用于`FluentIterable`。 检索到的元素将转换为元素列表; 元素是从`toString()`函数返回的字符串。

W
wizardforcel 已提交
324
```java
W
wizardforcel 已提交
325 326 327 328 329 330
[Car{id=3, name=Skoda, price=9000}, Car{id=4, name=Volvo, price=29000}]

```

This is the output of the example.

W
wizardforcel 已提交
331
## Guava 谓词
W
wizardforcel 已提交
332 333 334

一般而言,谓词是关于正确或错误的陈述。

W
wizardforcel 已提交
335
如果要测试的对象引用不是`null`,则`Predicates.notNull()`返回一个求值为`true`的谓词。
W
wizardforcel 已提交
336 337 338

`PredicateEx.java`

W
wizardforcel 已提交
339
```java
W
wizardforcel 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
package com.zetcode.predicateex;

import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.List;

public class PredicateEx {

    public static void main(String[] args) {

        List<Integer> values = Lists.newArrayList(3, null, 4, 7, 
                8, null, 7);

        Iterable<Integer> filtered = Iterables.filter(values, 
                Predicates.notNull());

        for (Integer i: filtered) {
            System.out.println(i);
        }
    }
}

```

在第一个示例中,我们使用谓词从集合中排除`null`值。

W
wizardforcel 已提交
367
```java
W
wizardforcel 已提交
368 369 370 371 372
List<Integer> values = Lists.newArrayList(3, null, 4, 7, 
        8, null, 7);

```

W
wizardforcel 已提交
373
使用 Guava 的`Lists.newArrayList()`,我们创建了`Integer`值的列表。 该列表包含两个`nulls`
W
wizardforcel 已提交
374

W
wizardforcel 已提交
375
```java
W
wizardforcel 已提交
376 377 378 379 380 381 382
Iterable<Integer> filtered = Iterables.filter(values, 
        Predicates.notNull());

```

我们通过应用`Predicates.notNull()`过滤值。 `Iterables.filter`返回一个可迭代的对象。

W
wizardforcel 已提交
383
```java
W
wizardforcel 已提交
384 385 386 387 388 389 390 391
for (Integer i: filtered) {
    System.out.println(i);
}

```

我们遍历过滤列表并打印其元素。

W
wizardforcel 已提交
392
```java
W
wizardforcel 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406
3
4
7
8
7

```

This is the output of the example.

第二个示例按特定的文本模式过滤集合。 在编程中,谓词通常用于过滤数据。

`PredicateEx2.java`

W
wizardforcel 已提交
407
```java
W
wizardforcel 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
package com.zetcode.predicateex;

import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;

public class PredicateEx2 {

    public static void main(String[] args) {

        List<String> items = Lists.newArrayList("coin", "book",
                "cup", "purse", "bottle");
        Collection<String> result  = Collections2.filter(items, 
                Predicates.containsPattern("o"));

        for (String item: result) {
            System.out.println(item);
        }
    }
}

```

该代码示例创建一个项目列表,然后按特定模式过滤该列表。

W
wizardforcel 已提交
435
```java
W
wizardforcel 已提交
436 437 438 439 440 441 442
Collection<String> result = Collections2.filter(items, 
        Predicates.containsPattern("o"));

```

`Predicates.containsPattern()`返回一个谓词,该谓词查找包含字符“ o”的项目。 谓词将传递给`Collections2.filter()`方法。

W
wizardforcel 已提交
443
```java
W
wizardforcel 已提交
444 445 446 447 448 449 450 451
coin
book
bottle

```

这三个词符合标准。

W
wizardforcel 已提交
452
## Guava `readLines()`
W
wizardforcel 已提交
453 454 455

`Files.readLines()`允许一次性读取文件中的所有行。

W
wizardforcel 已提交
456 457
![NetBeans project structure](img/3895f90623674f2736ca580e8e1af076.jpg)

W
wizardforcel 已提交
458
图:NetBeans 项目结构
W
wizardforcel 已提交
459 460 461 462 463 464 465



该图显示了项目结构在 NetBeans 中的外观。

`balzac.txt`

W
wizardforcel 已提交
466
```java
W
wizardforcel 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479
Honoré de Balzac, original name Honoré Balzac (born May 20, 1799, Tours, 
Francedied August 18, 1850, Paris) French literary artist who produced 
a vast number of novels and short stories collectively called 
La Comédie humaine (The Human Comedy). He helped to establish the traditional 
form of the novel and is generally considered to be one of the greatest 
novelists of all time.

```

我们在`src/main/resources`目录中有此文本文件。

`ReadingLinesEx.java`

W
wizardforcel 已提交
480
```java
W
wizardforcel 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
package com.zetcode.readinglinesex;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class ReadingLinesEx {

    public static void main(String[] args) throws IOException {

        String fileName = "src/main/resources/balzac.txt";

        List<String> lines = Files.readLines(new File(fileName), 
                Charsets.UTF_8);

        for (String line: lines) {
            System.out.println(line);
        }
    }
}

```

该示例从`balzac.txt`文件读取所有行,并将它们打印到控制台。

W
wizardforcel 已提交
508
```java
W
wizardforcel 已提交
509 510 511 512 513 514
String fileName = "src/main/resources/balzac.txt";

```

文件名位于`src/main/resource`目录中。

W
wizardforcel 已提交
515
```java
W
wizardforcel 已提交
516 517 518 519 520 521 522
List<String> lines = Files.readLines(new File(fileName), 
        Charsets.UTF_8);

```

使用`Files.readLines()`方法,我们从`balzac.txt`文件中读取所有行。 这些行存储在字符串列表中。

W
wizardforcel 已提交
523
```java
W
wizardforcel 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537
for (String line: lines) {
    System.out.println(line);
}

```

我们遍历列表并打印其元素。

## 使用 Guava 创建一个新文件

`Files.touch()`方法用于创建新文件或更新现有文件上的时间戳。 该方法类似于 Unix `touch`命令。

`TouchFileEx.java`

W
wizardforcel 已提交
538
```java
W
wizardforcel 已提交
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
package com.zetcode.touchfileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class TouchFileEx {

    public static void main(String[] args) throws IOException {

        String newFileName = "newfile.txt";

        Files.touch(new File(newFileName));
    }
}

```

该示例在项目的根目录中创建`newfile.txt`

## 用 Guava 写入文件

`Files.write()`方法将数据写入文件。

`WriteToFileEx.java`

W
wizardforcel 已提交
565
```java
W
wizardforcel 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
package com.zetcode.writetofileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class WriteToFileEx {

    public static void main(String[] args) throws IOException {

        String fileName = "fruits.txt";
        File file = new File(fileName);

        String content = "banana, orange, lemon, apple, plum";

        Files.write(content.getBytes(), file);
    }
}

```

该示例将由水果名称组成的字符串写入`fruits.txt`文件。 该文件在项目根目录中创建。

## 用 Guava 连接字符串

W
wizardforcel 已提交
591
`Joiner`用分隔符将文本片段(指定为数组,`Iterable`,可变参数或`Map`)连接在一起。
W
wizardforcel 已提交
592 593 594

`StringJoinerEx.java`

W
wizardforcel 已提交
595
```java
W
wizardforcel 已提交
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
package com.zetcode.stringjoinerex;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import java.util.List;

public class StringJoinerEx {

    public static void main(String[] args) {

        List<String> myList = Lists.newArrayList("8", "2", "7", "10");

        String result = Joiner.on(",").join(myList);

        System.out.println(result);
    }
}

```

在示例中,我们用逗号将列表中的元素连接起来。

W
wizardforcel 已提交
618
```java
W
wizardforcel 已提交
619 620 621 622 623 624
8,2,7,10

```

This is the output of the example.

W
wizardforcel 已提交
625
## 用 Guava 分割字符串
W
wizardforcel 已提交
626 627 628 629 630

`Splitter`通过识别分隔符序列的出现,从输入字符串中提取不重叠的子字符串。

`StringSplitterEx.java`

W
wizardforcel 已提交
631
```java
W
wizardforcel 已提交
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
package com.zetcode.stringsplitterex;

import com.google.common.base.Splitter;
import java.util.List;

public class StringSplitterEx {

    public static void main(String[] args) {

        String input = "There is a dog in the garden.";

        List<String> words = Splitter.on(" ").splitToList(input);

        for (String word: words) {
            System.out.println(word);
        }
    }
}

```

该示例使用`Splitter`将句子拆分为单词。

W
wizardforcel 已提交
655
```java
W
wizardforcel 已提交
656 657 658 659 660 661
String input = "There is a dog in the garden.";

```

我们有一个由七个词组成的句子。

W
wizardforcel 已提交
662
```java
W
wizardforcel 已提交
663 664 665 666 667 668 669 670 671 672
List<String> words = Splitter.on(" ").splitToList(input);

```

分隔符是一个空格字符。 `splitToList()`方法将输入拆分为字符串列表。

第二个示例将输入分为三个子字符串。

`StringSplitterEx2.java`

W
wizardforcel 已提交
673
```java
W
wizardforcel 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
package com.zetcode.stringsplitterex2;

import com.google.common.base.Splitter;
import java.util.List;

public class StringSplitterEx2 {

    public static void main(String[] args) {

        String input = "coin, pencil, chair, bottle, soap";

        List<String> words = Splitter.on(",")
                .trimResults()
                .limit(3)
                .splitToList(input);

        for (String word: words) {
            System.out.println(word);
        }
    }
}

```

此外,还对单词进行了修剪。

W
wizardforcel 已提交
700
```java
W
wizardforcel 已提交
701 702 703 704 705 706 707 708
coin
pencil
chair, bottle, soap

```

这是输出。

W
wizardforcel 已提交
709
## Guava 先决条件
W
wizardforcel 已提交
710 711 712 713 714

前提条件是简单的静态方法,将在我们自己的方法开始时调用它们以验证正确的参数和状态。 该方法在失败时抛出`IllegalArgumentException`

`PreconditionsEx.java`

W
wizardforcel 已提交
715
```java
W
wizardforcel 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
package com.zetcode.preconditionex;

import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Splitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class PreconditionsEx {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter items: ");
        String input = br.readLine();

        List<String> items = Splitter.on(" ").splitToList(input);
        OutputItems(items);
    }

    public static void OutputItems(List<String> items) {
        checkArgument(items != null, "The list must not be null");
        checkArgument(!items.isEmpty(), "The list must not be empty");

        for (String item: items) {
            System.out.println(item);
        }
    }
}

```

该示例使用两个前提条件。

W
wizardforcel 已提交
751
```java
W
wizardforcel 已提交
752 753 754 755 756 757 758 759
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter items: ");
String input = br.readLine();

```

我们从用户那里读取输入。 我们希望有一个单词列表。

W
wizardforcel 已提交
760
```java
W
wizardforcel 已提交
761 762 763 764 765 766 767
List<String> items = Splitter.on(" ").splitToList(input);
OutputItems(items);

```

将指定的单词拆分为一个列表,并将该列表传递给`OutputItems()`方法

W
wizardforcel 已提交
768
```java
W
wizardforcel 已提交
769 770 771 772 773
checkArgument(items != null, "The list must not be null");
checkArgument(!items.isEmpty(), "The list must not be empty");

```

W
wizardforcel 已提交
774
`OutputItems()`方法中,我们检查列表是否不为空。 使用`checkArgument()`方法,我们可以确保表达式的有效性; 例如该列表不为空。
W
wizardforcel 已提交
775

W
wizardforcel 已提交
776
## 用 Guava 计算阶乘
W
wizardforcel 已提交
777

W
wizardforcel 已提交
778
Guava 还提供用于进行数学计算的工具。 `BigIntegerMath.factorial()`计算阶乘。
W
wizardforcel 已提交
779 780 781

`FactorialEx.java`

W
wizardforcel 已提交
782
```java
W
wizardforcel 已提交
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
package com.zetcode.factorialex;

import com.google.common.math.BigIntegerMath;

public class FactorialEx {

    public static void main(String[] args) {

        System.out.println(BigIntegerMath.factorial(100));
    }
}

```

该示例显示数字 100 的阶乘。

W
wizardforcel 已提交
799
```java
W
wizardforcel 已提交
800 801 802 803 804 805
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

```

This is the output of the example.

W
wizardforcel 已提交
806
## 用 Guava 计算二项式
W
wizardforcel 已提交
807

W
wizardforcel 已提交
808
`BigIntegerMath.binomial()`返回`n``k`的二项式系数。
W
wizardforcel 已提交
809 810 811

`FactorialEx.java`

W
wizardforcel 已提交
812
```java
W
wizardforcel 已提交
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
package com.zetcode.binomialex;

import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;

public class BinomialEx {

    public static void main(String[] args) {

        BigInteger bigInt = BigIntegerMath.binomial(4, 2);
        System.out.println(bigInt);
    }
}

```

该示例显示 4 和 2 的二项式。

W
wizardforcel 已提交
831
## Guava `CharMatcher`
W
wizardforcel 已提交
832 833 834 835 836

`CharMatcher`提供了一些基本的文本处理方法。

`CharMatcherEx.java`

W
wizardforcel 已提交
837
```java
W
wizardforcel 已提交
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
package com.zetcode.charmatcherex;

import com.google.common.base.CharMatcher;

public class CharMatcherEx {

    public static void main(String[] args) {

        String input = "Peter17";

        CharMatcher matcher = CharMatcher.JAVA_LETTER;
        String result = matcher.retainFrom(input);

        System.out.println(result);
    }
}

```

该示例从输入字符串中删除所有非字母字符。 `retainFrom()`方法按顺序返回包含字符序列的所有匹配字符的字符串。

W
wizardforcel 已提交
859
```java
W
wizardforcel 已提交
860 861 862 863 864 865 866 867 868 869
Peter

```

两位数字被删除。

在第二个示例中,我们计算输入字符串中的字符数。

`CharMatcherEx2.java`

W
wizardforcel 已提交
870
```java
W
wizardforcel 已提交
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
package com.zetcode.charmatcherex2;

import com.google.common.base.CharMatcher;

public class CharMatcherEx2 {

    public static void main(String[] args) {

        String input = "Beautiful sunny day";

        int n1  = CharMatcher.is('n').countIn(input);
        System.out.format("Number of n characters: %d%n", n1);

        int n2  = CharMatcher.is('i').countIn(input);
        System.out.format("Number of i characters: %d", n2);
    }
}

```

该示例计算输入字符串中'n'和'i'字符的数量。

W
wizardforcel 已提交
893
```java
W
wizardforcel 已提交
894 895 896 897 898 899
int n1  = CharMatcher.is('n').countIn(input);

```

`countIn()`方法返回在字符序列中找到的匹配字符数。

W
wizardforcel 已提交
900
```java
W
wizardforcel 已提交
901 902 903 904 905 906 907 908 909 910 911
Number of n characters: 2
Number of i characters: 1

```

This is the output of the example.

`CharMatcher.whitespace()`确定字符是否为空格。

`CharMatcherEx3.java`

W
wizardforcel 已提交
912
```java
W
wizardforcel 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
package com.zetcode.charmatcherex3;

import com.google.common.base.CharMatcher;

public class CharMatcherEx3 {

    public static void main(String[] args) {

        String input = "   yogurt \t";

        String result = CharMatcher.whitespace().trimFrom(input);

        System.out.println(input + " and bread" );
        System.out.println(result + " and bread");
    }
}

```

在第三个示例中,我们从字符串中删除空格。

W
wizardforcel 已提交
934
```java
W
wizardforcel 已提交
935 936 937 938 939 940
String result = CharMatcher.whitespace().trimFrom(input);

```

空格从输入字符串中删除。

W
wizardforcel 已提交
941
```java
W
wizardforcel 已提交
942 943 944 945 946 947 948
   yogurt        and bread
yogurt and bread

```

This is the output of the example.

W
wizardforcel 已提交
949
## Guava `Range`
W
wizardforcel 已提交
950 951 952 953 954

`Range`可以轻松创建各种范围。 范围或间隔定义了连续值范围周围的边界; 例如 1 到 10 之间的整数(含 1 和 10)。

`RangeEx.java`

W
wizardforcel 已提交
955
```java
W
wizardforcel 已提交
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
package com.zetcode.rangeex;

import com.google.common.collect.Range;

public class RangeEx {

    public static void main(String[] args) {

        Range<Integer> range1 = Range.closed(3, 8);
        System.out.println(range1);

        Range<Integer> range2 = Range.openClosed(3, 8);
        System.out.println(range2);

        Range<Integer> range3 = Range.closedOpen(3, 8);
        System.out.println(range3);
    }
}

```

在示例中,我们创建了三个整数间隔。

W
wizardforcel 已提交
979
```java
W
wizardforcel 已提交
980 981 982 983 984 985 986 987 988 989
[38]
(38]
[38)

```

This is the output of the example.

在本文中,我们使用了 Google Guava 库。

W
wizardforcel 已提交
990
您可能也对以下相关教程感兴趣:[用 Java 阅读文本文件](/articles/javareadtext/)[Java 教程](/lang/java/)[用 Java 过滤列表](/articles/javafilterlist/)[Java8 的`StringJoiner`](/articles/java8stringjoiner/)[Opencsv 教程](/articles/opencsv/)