Java 8 添加了一个新的抽象称为流Stream,一个来自数据源的元素队列并支持聚合操作,不会存储元素,而是按需计算。
简单使用Stream提供的新方法forEach、map、filter、limit、sorted、collect
public static void main(String[] args) {
forEachTest();
mapTest();
filterTest();
limitTest();
sortedTest();
collectTest();
}
//forEach方法用于迭代数据
public static void forEachTest() {
List<String> list = Arrays.asList("aaa", "", "bbb", "ccc", "ddd","", "eee");
list.forEach(System.out::println);
list.forEach(c-> System.out.println(c));
list.forEach(c-> {System.out.println(c);});
}
//map方法用于映射每个元素到对应的结果
public static void mapTest() {
List<String> list = Arrays.asList("aaa", "", "bbb", "ccc", "ddd","", "eee");
List<String> mapList = list.stream().map(s->"map-"+s).collect(Collectors.toList());
mapList.forEach(System.out::println);
}
//filter方法用于通过设置的条件过滤出元素
public static void filterTest() {
List<String> strings = Arrays.asList("aaa", "", "bbb", "ccc", "ddd","", "eee");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty() && !string.equals("ccc")).collect(Collectors.toList());
filtered.forEach(c-> System.out.println(c));
}
//limit方法用于获取指定数量的流
public static void limitTest() {
List<String> list = Arrays.asList("aaa", "", "bbb", "ccc", "ddd","", "eee");
list.stream().limit(4).forEach(c-> System.out.println(c));
list.stream().limit(4).filter(l->!l.isEmpty()).forEach(c-> System.out.println(c));
list.stream().filter(l->!l.isEmpty()).limit(4).forEach(c-> System.out.println(c));
}
//sorted方法用于对流进行排序
public static void sortedTest() {
List<String> list = Arrays.asList("aaa", "", "fff", "ccc", "ddd","", "eee");
System.out.println("正序结果:");
list.stream().sorted().forEach(c-> System.out.println(c));
System.out.println("倒序结果:");
list.stream().sorted(Comparator.reverseOrder()).forEach(c-> System.out.println(c));
}
//collect方法用于归约操作,操作Collectors静态工厂类,将流转换成集合和聚合元素
public static void collectTest() {
List<String>strings = Arrays.asList("aaa", "", "bbb", "ccc", "ddd","", "eee","bbb");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("筛选列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).distinct().collect(Collectors.joining(", "));
System.out.println("去重后合并字符串: " + mergedString);
}
文章仅作为个人学习整理