Search in sources :

Example 6 with Person

use of com.huangjunlin.learning.model.Person in project java-code-show by CodeShowZz.

the class StreamTest method collectResultTest.

@Test
public void collectResultTest() {
    String[] names = { "Tom", "Jack", "Mary", "Adams", "HuangJunlin" };
    // 遍历流中的每一个元素
    Stream.of(names).forEach((x) -> {
        log.info(x);
    });
    // 流转换成数组
    String[] result = Stream.of(names).toArray(String[]::new);
    // 流转换成List
    List<String> result2 = Stream.of(names).collect(Collectors.toList());
    // 流转换成Set
    Set<String> result3 = Stream.of(names).collect(Collectors.toSet());
    // 流转换成TreeSet
    TreeSet<String> result4 = Stream.of(names).collect(Collectors.toCollection(TreeSet::new));
    // 将流中的元素元素直接连接起来
    String result5 = Stream.of(names).collect(Collectors.joining());
    // 将流中的元素连接起来 中间隔着特定的符号
    String result6 = Stream.of(names).collect(Collectors.joining(", "));
    // 对象要先转字符串才能连接起来
    List<Person> personList = new ArrayList<>();
    personList.add(new Person(1, "Tom"));
    personList.add(new Person(2, "Jack"));
    String result7 = personList.stream().map(Object::toString).collect(Collectors.joining(", "));
    // 统计流中的最大值 平均值 最小值等
    IntSummaryStatistics summary = Stream.of(names).collect(Collectors.summarizingInt(String::length));
    double averageWordLength = summary.getAverage();
    double maxWordLength = summary.getMax();
    log.info("averageWordLength:{}", averageWordLength);
    log.info("maxWordLength:{}", maxWordLength);
}
Also used : Person(com.huangjunlin.learning.model.Person) Test(org.junit.Test)

Aggregations

Person (com.huangjunlin.learning.model.Person)6 Test (org.junit.Test)4 BigInteger (java.math.BigInteger)2