Java8中使用filter()过滤列表,使用collect将stream转化为list

Reference: https://www.mkyong.com/java8/java-8-streams-filter-examples/

/*
 In Java 8, using stream.filter() to filter a List, and collect() to convert a stream.
 */

import java.util.*;
import java.util.stream.Collectors;

public class Exercise {
  
  public static void main(String args[]) {
    List<String> lines = Arrays.asList("spring", "node", "mkyong");
    List<String> result0 = getFilterOutput(lines, "mkyong");
    // output "spring", "node"
    for (String temp : result0) {
      System.out.println(temp);
    }

    /* The equivalent example in Java 8, using stream.filter() to
  filter a list, and collect() to convert a stream.
   */
    List<String> result1 = lines.stream()  // convert list to stream
        .filter(line -> !"mkyong".equals(line)) // filter the line which equals to "mkyong"
        .collect(Collectors.toList());  // collect the output and convert streams to a list

    result1.forEach(System.out::println); // output "spring", "node"
  }

  private static List<String> getFilterOutput(List<String> lines, String filter) {
    List<String> result = new ArrayList<>();
    for (String line : lines) {
      if (!"mkyong".equals(line)) {
        result.add(line);
      }
    }
    return result;
  }

}
    原文作者:huludan
    原文地址: https://blog.csdn.net/huludan/article/details/54316387
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞