87.md 21.0 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 17 18 19 20 21 22 23 24 25

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

```
<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 32 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

`InitializeCollectionEx.java`

```
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

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

```

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

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

```

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

```
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 99 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

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

`Car.java`

```
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()`方法,该方法给出对象的字符串表示形式。

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

```

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

`ToStringEx.java`

```
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()`方法。

```
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 208 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 265 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

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

`Car.java`

```
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`

```
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 298 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 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

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

```

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

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

```

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

```
[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 335 336 337 338 339 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 367 368 369 370 371 372

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

如果要测试的对象引用不是`null`,则`Predicates.notNull()`返回一个评估为 true 的谓词。

`PredicateEx.java`

```
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`值。

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

```

W
wizardforcel 已提交
373
使用Guava 的`Lists.newArrayList()`,我们创建了`Integer`值的列表。 该列表包含两个`nulls`
W
wizardforcel 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 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 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

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

```

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

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

```

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

```
3
4
7
8
7

```

This is the output of the example.

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

`PredicateEx2.java`

```
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);
        }
    }
}

```

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

```
Collection<String> result = Collections2.filter(items, 
        Predicates.containsPattern("o"));

```

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

```
coin
book
bottle

```

这三个词符合标准。

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

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

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

Figure: NetBeans project structure
W
wizardforcel 已提交
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 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 565 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 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624



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

`balzac.txt`

```
Honoré de Balzac, original name Honoré Balzac (born May 20, 1799, Tours, 
France—died 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`

```
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`文件读取所有行,并将它们打印到控制台。

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

```

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

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

```

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

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

```

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

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

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

`TouchFileEx.java`

```
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`

```
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 连接字符串

`Joiner`用分隔符将文本片段(指定为数组,`Iterable`,varargs 或`Map`)连接在一起。

`StringJoinerEx.java`

```
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);
    }
}

```

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

```
8,2,7,10

```

This is the output of the example.

W
wizardforcel 已提交
625
## 用 Guava 分割字符串
W
wizardforcel 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 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 700 701 702 703 704 705 706 707 708

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

`StringSplitterEx.java`

```
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`将句子拆分为单词。

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

```

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

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

```

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

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

`StringSplitterEx2.java`

```
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);
        }
    }
}

```

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

```
coin
pencil
chair, bottle, soap

```

这是输出。

W
wizardforcel 已提交
709
## Guava 先决条件
W
wizardforcel 已提交
710 711 712 713 714 715 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 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775

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

`PreconditionsEx.java`

```
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);
        }
    }
}

```

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

```
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);

```

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

```
checkArgument(items != null, "The list must not be null");
checkArgument(!items.isEmpty(), "The list must not be empty");

```

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

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

W
wizardforcel 已提交
778
Guava 还提供用于进行数学计算的工具。 `BigIntegerMath.factorial()`计算阶乘。
W
wizardforcel 已提交
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805

`FactorialEx.java`

```
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 的阶乘。

```
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

```

This is the output of the example.

W
wizardforcel 已提交
806
## 用 Guava 计算二项式
W
wizardforcel 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830

`BigIntegerMath.binomial()`返回 n 和 k 的二项式系数。

`FactorialEx.java`

```
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 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

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

`CharMatcherEx.java`

```
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()`方法按顺序返回包含字符序列的所有匹配字符的字符串。

```
Peter

```

两位数字被删除。

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

`CharMatcherEx2.java`

```
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'字符的数量。

```
int n1  = CharMatcher.is('n').countIn(input);

```

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

```
Number of n characters: 2
Number of i characters: 1

```

This is the output of the example.

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

`CharMatcherEx3.java`

```
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");
    }
}

```

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

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

```

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

```
   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 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990

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

`RangeEx.java`

```
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);
    }
}

```

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

```
[3‥8]
(3‥8]
[3‥8)

```

This is the output of the example.

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

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