public class DemoTest1 {
public static void main(String[] args) {
List<String> languages = Arrays.asList("Java", "Python", "C++", "Lisp", "Haskell", "Scala");
// 值为 “J” 开头
languages.stream().filter((str)->str.startsWith("J")).forEach(System.out::println);
// 值为 “a” 结尾
languages.stream().filter((str)->str.endsWith("a")).forEach(System.out::println);
// 输出全部
languages.stream().filter((str)->true).forEach(System.out::println);
// 长度大于4
languages.stream().filter((str)->str.length()>4).forEach(System.out::println);
}
}
public class DemoTest2 {
public static void main(String[] args) {
List<String> languages = Arrays.asList("Java", "Python", "C++", "Lisp", "Haskell", "Scala");
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
languages.stream().filter(startsWithJ.and(fourLetterLong)).forEach(System.out::println);
}
}
public class DemoTest3 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(100, 200, 300, 400, 500);
list.stream().map((cost) -> cost + .12 * cost).forEach(System.out::println);
}
}
reduce() 方法:同样可以接受 lambda 表达式,然后对所有的值进行合并
public class DemoTest4 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(100, 200, 300, 400, 500);
Double sum = list.stream().map((cost) -> cost + .12 * cost).reduce(Double::sum).get();
System.out.println(sum);
}
}
public class DemoTest5 {
public static void main(String[] args) {
List<String> fileNames = Arrays.asList("EDMMICabc20230625","bcd","EDMMICdefg20230625","jk");
Predicate<String> p1 = (n) -> n.startsWith("EDMMIC");
Predicate<String> p2 = (n) -> n.endsWith("20230625");
List<String> list = fileNames.stream().filter(p1.and(p2)).collect(Collectors.toList());
list.forEach(System.out::println);
}
}
public class DemoTest6 {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
List<Integer> collect = numbers.stream().distinct().collect(Collectors.toList());
System.out.println(numbers);
System.out.println(collect);
}
}
public class DemoTest7 {
public static void main(String[] args) {
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics statistics = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println(statistics.getMax()); // 最大值
System.out.println(statistics.getMin()); // 最小值
System.out.println(statistics.getSum()); // 总和
System.out.println(statistics.getAverage()); // 平均值
}
}