JDK8新特性之Stream流详解

概念

Stream是Java8 API的新成员,它允许以声明性方式处理数据集合 。

Stream可以由数组或集合创建,对流的操作分为两种:

中间操作,每次返回一个新的流,可以有多个。
终端操作,每个流只能进行一次终端操作,终端操作结束后流无法再次使用。终端操作会产生一个新的集合或值。
另外,Stream有几个特性:

stream不存储数据,而是按照特定的规则对数据进行计算,一般会输出结果。
stream不会改变数据源,通常情况下会产生一个新的集合或一个值。
stream具有延迟执行特性,只有调用终端操作时,中间操作才会执行。

流程

1)第一步:把集合转换为流stream
2)第二步:操作stream流
stream流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果

操作符

两种:中间操作符、终止操作符

中间操作符

流方法 含义 示例
filter 用于通过设置的条件过滤出元素 List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
distinct 返回一个元素各异(根据流所生成元素的hashCode和equals方法实现)的流。 List numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
limit 会返回一个不超过给定长度的流。 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");List limited = strings.stream().limit(3).collect(Collectors.toList());
skip 返回一个扔掉了前n个元素的流。 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");List skiped = strings.stream().skip(3).collect(Collectors.toList());
map 接受一个函数作为参数。这个函数会被应用到每个元素上,并将其映射成一个新的元素(使用映射一词,是因为它和转换类似,但其中的细微差别在于它是“创建一个新版本”而不是去“修改”)。 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");List mapped = strings.stream().map(str->str+"-itcast").collect(Collectors.toList());
flatMap 使用flatMap方法的效果是,各个数组并不是分别映射成一个流,而是映射成流的内容。所有使用map(Arrays::stream)时生成的单个流都被合并起来,即扁平化为一个流。 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");Stream flatMap = strings.stream().flatMap(Java8StreamTest::getCharacterByString);
sorted 返回排序后的流 List strings1 = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");List sorted1 = strings1.stream().sorted().collect(Collectors.toList());

示例代码:

1)filter

/**
 * 功能描述:根据条件过滤集合数据
 * @return : void
*/
@Test
public void filter(){
 List strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
 List filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 out.println(filtered);
}

2)distinct

/**
 * 功能描述:去除集合中重复数据
 * @return : void
*/
@Test
public void distinct(){
 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");
 List distincted = strings.stream().distinct().collect(Collectors.toList());
 out.println(distincted);
}

3)limit

/**
 * 功能描述:指定获取集合前x条数据,重新构造一个新的集合
 * @return : void
*/
@Test
public void limit(){
 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");
 List limited = strings.stream().limit(3).collect(Collectors.toList());
 out.println(limited);
}

4)skip

/**
 * 功能描述:排除集合前x条数据,把后面的数据重新构造一个新的集合
 * @return : void
*/
@Test
 public void skip(){
 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");
 List skiped = strings.stream().skip(3).collect(Collectors.toList());
 out.println(skiped);
}

5)map

/**
 * 功能描述:对集合中所有元素统一处理
 * @return : void
*/
@Test
public void map(){
 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");
 List mapped = strings.stream().map(str->str+"-itcast").collect(Collectors.toList());
 out.println(mapped);
}

6)flatMap

/**
 * 功能描述:对集合中所有元素统一处理
 * @return : void
*/
@Test
public void flatMap(){
 List strings = Arrays.asList("abc", "abc", "bc", "efg", "abcd","jkl", "jkl");
 Stream stringStream = strings.stream().map(x -> x);
 Stream stringStream1 = strings.stream().flatMap(x -> Arrays.asList(x.split(" ")).stream());
}

7)sorted

/**
 * 功能描述 : 对集合进行排序
 * @return : void
*/
@Test
public void sorted(){
 List strings1 = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");
 List strings2 = Arrays.asList("张三", "李四", "王五", "赵柳", "张哥","李哥", "王哥");
 List strings3 = Arrays.asList(10, 2, 30, 22, 1,0, -9);
 List sorted1 = strings1.stream().sorted().collect(Collectors.toList());
 List sorted2 = strings2.stream().sorted(Collections.reverseOrder(Collator.getInstance(Locale.CHINA))).collect(Collectors.toList());
 List sorted3 = strings3.stream().sorted().collect(Collectors.toList());
 out.println(sorted1);
 out.println(sorted2);
 out.println(sorted3);
}

 
  

终止操作符

流方法 含义 示例
anyMatch 检查是否至少匹配一个元素,返回boolean。 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");boolean b = strings.stream().anyMatch(s -> s == "abc");
allMatch 检查是否匹配所有元素,返回boolean。 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");boolean b = strings.stream().allMatch(s -> s == "abc");
noneMatch 检查是否没有匹配所有元素,返回boolean。 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");boolean b = strings.stream().noneMatch(s -> s == "abc");
findAny 将返回当前流中的任意元素。 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");Optional any = strings.stream().findAny();
findFirst 返回第一个元素 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");Optional first = strings.stream().findFirst();
forEach 遍历流 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");strings.stream().forEach(s -> out.println(s));
collect 收集器,将流转换为其他形式。 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");Set set = strings.stream().collect(Collectors.toSet());List list = strings.stream().collect(Collectors.toList());Map map = strings.stream().collect(Collectors.toMap(v ->v.concat("_name"), v1 -> v1, (v1, v2) -> v1));
reduce 可以将流中元素反复结合起来,得到一个值。 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");Optional reduce = strings.stream().reduce((acc,item) -> {return acc+item;});if(reduce.isPresent())out.println(reduce.get());
count 返回流中元素总数。 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");long count = strings.stream().count();

示例代码

1)anyMatch

/**
 * 功能描述 : 判断集合中是否至少存在一个元素满足条件
 * @return : void
*/
@Test
public void anyMatch(){
 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");
 boolean b = strings.stream().anyMatch(s -> s == "abc");
 out.println(b);
}

2)allMatch

/**
 * 功能描述 : 判断集合中是否所有元素都满足条件
 * @return : void
*/
@Test
public void allMatch(){
 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");
 boolean b = strings.stream().allMatch(s -> s == "abc");
 out.println(b);
}

3)noneMatch

/**
 * 功能描述 : 判断集合中是否所有元素都不满足条件
 * @return : void
*/
@Test
public void noneMatch(){
 List strings = Arrays.asList("abc", "abd", "aba", "efg", "abcd","jkl", "jkl");
 boolean b = strings.stream().noneMatch(s -> s == "abc");
 out.println(b);
}

4)findAny

/**
 * 功能描述 : 返回当前流中任意元素
 * @return : void
*/
@Test
public void findAny(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 Optional any = strings.stream().findAny();
 if(any.isPresent()) out.println(any.get());
}

5)findFirst

/**
 * 功能描述 : 返回当前流中第一个元素
 * @return : void
*/
@Test
public void findFirst(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 Optional first = strings.stream().findFirst();
 if(first.isPresent()) out.println(first.get());
}

6)forEach java

/**
 * 功能描述 : 遍历流
 * @return : void
*/
@Test
public void foreach(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 strings.stream().forEach(s -> out.println(s));
}

7)collect

/**
 * 功能描述 : 流转换为其他形式
 * @return : void
*/
@Test
public void collect(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 Set set = strings.stream().collect(Collectors.toSet());
 List list = strings.stream().collect(Collectors.toList());
 Map map = strings.stream().collect(Collectors.toMap(v ->v.concat("_name"), v1 -> v1, (v1, v2) -> v1));
 out.println(set);
 out.println(list);
 out.println(map);
}

8)reduce

/**
 * 功能描述 : 将流中元素反复结合起来,得到一个值
 * @return : void
*/
@Test
public void reduce(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 //reduce方法一
 Optional reduce1 = strings.stream().reduce((acc,item) -> {return acc+item;});
 //reduce方法二
 String reduce2 = strings.stream().reduce("itcast", (acc, item) -> {
    return acc + item;
 });
 //reduce方法三
 ArrayList reduce3 = strings.stream().reduce(
     new ArrayList(),
        new BiFunction, String, ArrayList>() {
        @Override
        public ArrayList apply(ArrayList acc, String item) {
            acc.add(item);
            return acc;
        }
    }, 
     new BinaryOperator>() {
            @Override
        public ArrayList apply(ArrayList acc, ArrayList item) {
        return acc;
        }
    }
 );
 if(reduce1.isPresent())out.println(reduce1.get());
 out.println(reduce2);
 out.println(reduce3);
}

9)count

/**
* 功能描述 : 返回流中元素总数
* @return : void
*/
@Test
public void count(){
 List strings = Arrays.asList("cv", "abd", "aba", "efg", "abcd","jkl", "jkl");
 long count = strings.stream().count();
 out.println(count);
}

你可能感兴趣的:(java,开发语言)