本章概述:本章主要讲了Stream特性,Stream运行机制,Stream的创建,Stream常用API,以及Stream API在实际应用开发中的作用
目录
本章概述:
一、annotation
1、AnnotationDemo
package class7.annotation;
import java.util.Date;
//@SuppressWarnings("all")
public class AnnotationDemo {
private int num;
@Override
public String toString() {
return "AnnotationDemo{" +
"num=" + num +
'}';
}
/**
* 计算两个整数相加的和
*
* @param num1 第一个数
* @param num2 第二个数
* @return
* 两个数相加的和
*/
public int add(int num1,int num2){
return num1+num2;
}
@Deprecated
public void test(){
System.out.println("test");
}
public static void main(String[] args) {
AnnotationDemo ad = new AnnotationDemo();
// ad.test();
//使用反射技术创建对象
try {
AnnotationDemo ad2 = (AnnotationDemo)Class.forName("class7.annotation.AnnotationDemo").newInstance();
ad2.test();
} catch (Exception e) {
e.printStackTrace();
}
Date date = new Date();
System.out.println(date.getYear());
}
}
2、FunctionInterfaceDemo
package class7.annotation;
@FunctionalInterface
public interface FunctionInterfaceDemo {
// void add(int a,int b);
void sub(int a, int b);
}
3、MetaAnnotation
package class7.annotation;
import java.lang.annotation.*;
@MyAnnotation(age = 20,joys = {"a","b","c"})
public class MetaAnnotation {
public void print(){
System.out.println("print... ...");
}
}
//自定义注解
//target是说明自定义注解在什么位置可以使用,包、类、方法、属性等等
@Target({ElementType.METHOD,ElementType.TYPE})
//retention说明当前注解可以适用的环境,或者说什么级别保存注释信息,有三个级别,源码级别SOURCE、类级别CLASS,运行时环境RUNTIME,默认一般是RUNTIME级别
@Retention(RetentionPolicy.RUNTIME)
//说明注解是否可以显示在javadoc中
@Documented
//说明当前注解是否能被继承
@Inherited
@interface MyAnnotation{
//定义的方式看起来像是方法,但是实际上在使用注解的时候需要配置的一些参数名称和类型,默认的名称是value
//自定义注解的中填写的参数名称对应方法名,参数的类型对应方法的返回类型,需要一个一个的添加,写起来很麻烦,因此一般给它一些默认值。
int id() default 1;
String name() default "";
int age() default 18;
String[] joys() default "";
}
4、Test1
package class7.annotation;
public class Test1 {
public void test(){
System.out.println("test");
}
}
二、lambda
1、Demo1
package class7.lambda;
import java.util.function.*;
public class Demo1 {
public void getNum(int num){
System.out.println("getNum:" + num);
}
public String toUpperCase(String str){
return str.toUpperCase();
}
public Integer getLength(String str1,String str2){
return str1.length() + str2.length();
}
public int get(){
return 1;
}
public static void main(String[] args) {
// new Demo1().getNum(100);
//使用new关键字实例(instance)化一个对象
// Demo1 d = new Demo1();
Consumer<Integer> c1 = (num)->new Demo1().getNum(num);
Consumer<Integer> c2 = new Demo1()::getNum;
c1.accept(200);
c2.accept(300);
Function<String,String> f1 = (str)->str.toUpperCase();
Function<String,String> f2 = (str)->new Demo1().toUpperCase(str);
Function<String,String> f3 = new Demo1()::toUpperCase;
System.out.println(f1.apply("abcdefg"));
System.out.println(f2.apply("abc"));
System.out.println(f3.apply("abc"));
UnaryOperator<String> uo = (str)->new Demo1().toUpperCase(str);
UnaryOperator<String> uo2 = new Demo1()::toUpperCase;
System.out.println(uo.apply("abcdefghijk"));
System.out.println(uo2.apply("abcd"));
BiFunction<String,String,Integer> bf1 = new BiFunction<String, String, Integer>() {
@Override
public Integer apply(String s, String s2) {
return new Demo1().getLength(s,s2);
}
};
System.out.println(bf1.apply("老于", "贼帅"));
BiFunction<String,String,Integer> bf2 = (str1,str2)->new Demo1().getLength(str1,str2);
BiFunction<String,String,Integer> bf3 = new Demo1()::getLength;
BiFunction<String,String,Integer> bf4 = (str1,str2)->{
return new Demo1().getLength(str1,str2);
};
System.out.println(bf2.apply("abc", "bcd"));
System.out.println(bf3.apply("老于", "贼帅"));
System.out.println(bf4.apply("老于", "贼帅"));
Supplier<Integer> s1 = new Demo1()::get;
System.out.println(s1.get());
}
}
2、Demo2
package class7.lambda;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* @author Jason Yu
* @version 1.0
*/
public class Demo2 {
public static void main(String[] args) {
Consumer<Foo> c1 = new Consumer<Foo>() {
@Override
public void accept(Foo foo) {
// new Foo().get();
// new Foo2().get();
foo.get();
}
};
c1.accept(new Foo());
Consumer<Foo> c2 = (foo)->new Foo().get();
Consumer<Foo> c3 = (foo)->new Foo2().get(); //不常用
Consumer<Foo> c4 = (foo)->foo.get(); //不常用
Consumer<Foo> c5 = Foo::get;
c2.accept(new Foo());
c3.accept(new Foo());
c4.accept(new Foo());
c5.accept(new Foo());
Function<Foo,Integer> f1 = (foo)->new Foo().print();
Function<Foo,Integer> f2 = Foo::print;
f1.apply(new Foo());
f2.apply(new Foo());
BiConsumer<Foo2,String> bc1 = (foo,name)->new Foo2().show(name);
BiConsumer<Foo2,String> bc2 = Foo2::show;
// BiConsumer<String,Foo2> bc3 = Foo2::show; //错误
bc1.accept(new Foo2(),"zhaoyun");
bc2.accept(new Foo2(),"guanyu");
}
}
class Foo{
public void get(){
System.out.println("Foo--get");
}
public int print(){
System.out.println("Foo---print");
return 1;
}
}
class Foo2{
public void get(){
System.out.println("Foo2---get");
}
public int print(){
System.out.println("Foo2---print");
return 2;
}
public void show(String name){
System.out.println("Foo2----show---" + name);
}
}
3、Demo3
package class7.lambda;
import jdk.nashorn.internal.ir.FunctionNode;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
public class Demo3 {
public static void main(String[] args) {
// Supplier<Person> s1 = new Supplier<Person>() {
// @Override
// public Person get() {
// return new Person();
// }
// };
// s1.get();
Supplier<Person> s2 = ()->new Person();
Supplier<Person> s3 = ()->{return new Person();};
Supplier<Person> s4 = Person::new;
s2.get();
s3.get();
s4.get();
// Function<String,User> f = new Function<String, User>() {
// @Override
// public User apply(String s) {
// return new User(s);
// }
// };
Function<String,User> f1 = (name)->new User(name);
Function<String,User> f2 = User::new;
f1.apply("zhangfei");
f2.apply("guanyu");
Function<Integer,User> f3 = (age)->new User(age);
Function<Integer,User> f4 = User::new;
f3.apply(25);
f4.apply(30);
List<String> list = Arrays.asList("a", "b", "c", "d", "e");
// for (String s : list) {
// System.out.println(s);
// }
list.forEach(System.out::println);
}
}
class User{
public User(){
System.out.println("User的空构造方法被调用了... ...");
}
public User(String name){
System.out.println("User含有name的构造方法被调用了... ..." + name);
}
public User(int age){
System.out.println("User含有age的构造方法被调用了... ..." + age);
}
}
class Person{
public Person(){
System.out.println("Person的空构造方法被调用了... ...");
}
}
三、stream
1、StreamDemo
package class7.stream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamDemo {
//通过数组生成
public static void generate1(){
String[] strs = {"a","b","c","d","e"};
Stream<String> stringStream = Stream.of(strs);
stringStream.forEach(System.out::println);
}
//通过集合生成
public static void generate2(){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = list.stream();
stream.forEach(System.out::println);
}
//通过generate生成
public static void generate3(){
//生成10个1
Stream<Integer> stream = Stream.generate(() -> 1);
stream.limit(10).forEach(System.out::println);
}
//通过iterate生成
public static void generate4(){
//生成1-10的整数
// Stream<Integer> stream = Stream.generate(() -> {
// int i = 1;
// for(;i<=100;i++){
// System.out.println(i);
// }
// return i;
// });
Stream<Integer> stream = Stream.iterate(1, (x) -> x + 1);
stream.limit(10).forEach(System.out::println);
}
//通过其他API创建
public static void generate5(){
String str = "abcdefg";
IntStream intStream = str.chars();
intStream.forEach(System.out::println);
}
public static void main(String[] args) {
// List<String> list = Arrays.asList("go", "java", "python", "scala", "javascript");
// list.forEach(System.out::println);
generate1();
generate2();
generate3();
System.out.println("*******************************");
generate4();
generate5();
//中间操作:如果调用方法之后返回的结果是Stream对象就意味着是一个中间操作
Arrays.asList(1, 2, 3, 4, 5, 6).stream().filter(x -> x%2==0).forEach(System.out::println);
System.out.println("*****************************");
//原来的写法
// List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
//1、for循环遍历
// for(int i = 0; i < list.size();i++){
// if(list.get(i) % 2 == 0){
// System.out.println(list.get(i));
// }
// }
//2、迭代器iterator遍历
// Iterator<Integer> iterator = list.iterator();
// while(iterator.hasNext()){
// Integer next = iterator.next();
// if(next % 2 == 0){
// System.out.println(next);
// }
// }
//3、增强for循环
// for (Integer integer : list) {
// if (integer % 2 == 0) {
// System.out.println(integer);
// }
// }
List<Integer> list = Arrays.asList(1, 2,3, 4,5, 6);
//求出结果集中所有偶数的和
int sum = list.stream().filter(x -> x % 2 == 0).mapToInt(x -> x).sum();
System.out.println(sum);
//求集合中的最大值
Optional<Integer> max = list.stream().max((a,b)->a-b);
System.out.println(max.get());
// 原来的写法?
//求集合的最小值
Optional<Integer> min = list.stream().min((a, b) -> a - b);
System.out.println(min.get());
//交流分享时间:让原来你们的师哥跟大家分享一些学习方法和经验。
//原来的写法?
Optional<Integer> any = list.stream().filter(x -> x % 2 == 0).findAny();
System.out.println(any.get());
Optional<Integer> first = list.stream().filter(x -> x % 10 == 6).findFirst();
System.out.println(first.get());
Stream<Integer> integerStream = list.stream().filter(i -> {
System.out.println("运行代码!");
return i % 2 == 0;
});
integerStream.findFirst();
// System.out.println(integerStream.findFirst().get());
// System.out.println(integerStream.findAny().get());
//获取最大值和最小值但是不使用min和max方法
Optional<Integer> min2 = list.stream().sorted().findFirst();
System.out.println(min2.get());
Optional<Integer> max2 = list.stream().sorted((a, b) -> b - a).findFirst();
System.out.println(max2.get());
Arrays.asList("go","python","scala","java","javascript").stream().sorted().forEach(System.out::println);
Arrays.asList("go","python","scala","java","javascript").stream().sorted((a,b)->a.length()-b.length()).forEach(System.out::println);
//原来的写法?(如果不使用比较器如何编写代码?)
//想将集合中的元素进行过滤同时返回一个集合对象
List<Integer> list1 = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
list1.forEach(System.out::println);
//去重操作
Stream<Integer> integerStream1 = Arrays.asList(1, 2, 2, 2, 3, 4, 4, 5).stream().distinct();
integerStream1.forEach(System.out::println);
System.out.println("**************************************");
Set<Integer> set = Arrays.asList(1, 2, 2, 2, 3, 4, 4, 5).stream().collect(Collectors.toSet());
set.forEach(System.out::println);
//打印20-30这样的集合数据
Stream.iterate(1,x->x+1).limit(30).skip(20).limit(10).forEach(System.out::println);
String str = "10,20,30,40,50,60";
//原来的写法?
// String[] strs = str.split(",");
// int sum1 = 0;
// for (String s : strs) {
// sum1 += Integer.valueOf(s);
// }
// System.out.println(sum1);
System.out.println(Stream.of(str.split(",")).mapToInt(x -> Integer.valueOf(x)).sum());
System.out.println(Stream.of(str.split(",")).mapToInt(Integer::valueOf).sum());
System.out.println(Stream.of(str.split(",")).map(x -> Integer.valueOf(x)).mapToInt(x -> x).sum());
System.out.println(Stream.of(str.split(",")).map(Integer::valueOf).mapToInt(x -> x).sum());
//创建一组自定义对象
String names = "曹颍,陈卓,张川南,杨淼,乔玉祯";
//原来的写法?
// String[] nameArray = names.split(",");
// Student student = new Student();
// for (String s : nameArray) {
// student.setName(s);
// System.out.println(student);
// }
Stream.of(names.split(",")).map(name->new Student(name)).forEach(System.out::println);
Stream.of(names.split(",")).map(Student::new).forEach(System.out::println);
System.out.println("***************************************************");
Stream.of(names.split(",")).map(name->Student.getStudent(name)).forEach(System.out::println);
Stream.of(names.split(",")).map(Student::getStudent).forEach(System.out::println);
//将str中的每一个数值都打印出来,同时算出最终的求和结果
String str2 = "1,2,3,4,5,6,7,8,9";
System.out.println(Stream.of(str2.split(",")).peek(System.out::println).mapToInt(Integer::valueOf).sum());
System.out.println(list.stream().allMatch(x -> x > 2));
System.out.println(list.stream().anyMatch(x -> x > 2));
System.out.println(list.stream().count());
//练习题一
/**
* 类:订单类Order
* 属性:
* -oId(String) 订单号
* -proName(String) 商品名称
* -proNum(int) 商品数量
* -totalPrice(double) 总价
*
* 需求:
* 1、先使用集合存储几个订单;
* 2、然后把订单总价大于2000的订单转存到一个集合中;
* 3、遍历集合,输出所有订单中总价大于2000的订单信息。
*/
//练习题二
/**
* 类:商品类Product
* * 属性:
* * -pNo(String) 商品编号
* * -pName(String) 商品名称
* * -pPrice(double) 商品单价
* * -pDesc(String) 商品描述
* * -pSum(int) 库存量
* 类:订单类Order
* 属性:
* -oId(String) 订单号
* -pNo(String) 商品编号
* -pNum(int) 购买总数量
* -totalPrice(double) 总价
*
* 需求:
* 1、先使用集合存储几个商品和订单,注意订单和商品的关系;
* 2、然后把订单总价大于2000的订单转存到一个集合中;
* 3、并最终输出总价大于2000的商品信息。
*/
}
}
2、Student
package class7.stream;
public class Student {
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//定义方法获取一个学生对象
public static Student getStudent(String name){
Student student = new Student();
student.setName(name);
return student;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
'}';
}
}