常用类
String
- String s1 = “javaEE”; 通过字面量定义的方式:此时的s1的数据javaEE声明在方法区中的字符串常量池中
- String s3 = new String(“javaEE”); 通过new + 构造器的方式:此时的s3保存的地址值,是数据在堆空间中开辟空间以后对应的地址值
常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。只要其中有一个是变量,结果就在堆中;见test4 ```java /* String:字符串,使用一对””引起来表示。 1.String声明为final的,不可被继承 2.String实现了Serializable接口:表示字符串是支持序列化的。
实现了Comparable接口:表示String可以比较大小
3.String内部定义了final char[] value用于存储字符串数据 4.String:代表不可变的字符序列。简称:不可变性。
体现:1.当对字符串重新赋值时,需要重写指定内存区域赋值,不能使用原有的value进行赋值。2. 当对现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。3. 当调用String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
5.通过字面量的方式(区别于new)给一个字符串赋值,此时的字符串值声明在字符串常量池中。 6.字符串常量池中是不会存储相同内容的字符串的。 */ @Test public void test1(){
String s1 = "abc";//字面量的定义方式String s2 = "abc";s1 = "hello";System.out.println(s1 == s2);//比较s1和s2的地址值System.out.println(s1);//helloSystem.out.println(s2);//abcSystem.out.println("*****************");String s3 = "abc";s3 += "def";System.out.println(s3);//abcdefSystem.out.println(s2);System.out.println("*****************");String s4 = "abc";String s5 = s4.replace('a', 'm');System.out.println(s4);//abcSystem.out.println(s5);//mbc
}
/*String的实例化方式:方式一:通过字面量定义的方式方式二:通过new + 构造器的方式面试题:String s = new String("abc");方式创建对象,在内存中创建了几个对象?两个:一个是堆空间中new结构,另一个是char[]对应的常量池中的数据:"abc"*/@Testpublic void test2(){//通过字面量定义的方式:此时的s1和s2的数据javaEE声明在方法区中的字符串常量池中。String s1 = "javaEE";String s2 = "javaEE";//通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值。String s3 = new String("javaEE");String s4 = new String("javaEE");System.out.println(s1 == s2);//trueSystem.out.println(s1 == s3);//falseSystem.out.println(s1 == s4);//falseSystem.out.println(s3 == s4);//falseSystem.out.println("***********************");Person p1 = new Person("Tom",12);Person p2 = new Person("Tom",12);System.out.println(p1.name.equals(p2.name));//trueSystem.out.println(p1.name == p2.name);//truep1.name = "Jerry";System.out.println(p2.name);//Tom}/*结论:1.常量与常量的拼接结果在常量池。且常量池中不会存在相同内容的常量。2.只要其中有一个是变量,结果就在堆中。3.如果拼接的结果调用intern()方法,返回值就在常量池中*/@Testpublic void test4(){String s1 = "javaEEhadoop";String s2 = "javaEE";String s3 = s2 + "hadoop";System.out.println(s1 == s3);//falsefinal String s4 = "javaEE";//s4:常量String s5 = s4 + "hadoop";System.out.println(s1 == s5);//true}@Testpublic void test3(){String s1 = "javaEE";String s2 = "hadoop";String s3 = "javaEEhadoop";String s4 = "javaEE" + "hadoop";String s5 = s1 + "hadoop";String s6 = "javaEE" + s2;String s7 = s1 + s2;System.out.println(s3 == s4);//trueSystem.out.println(s3 == s5);//falseSystem.out.println(s3 == s6);//falseSystem.out.println(s3 == s7);//falseSystem.out.println(s5 == s6);//falseSystem.out.println(s5 == s7);//falseSystem.out.println(s6 == s7);//falseString s8 = s6.intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”System.out.println(s3 == s8);//true}
<a name="nBY3N"></a>####<a name="ozrtu"></a>#### StringBuffer & StringBuilder & String- String:不可变的字符序列;底层使用char[]存储- StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储- StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储```java/*String、StringBuffer、StringBuilder三者的异同?String:不可变的字符序列;底层使用char[]存储StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储源码分析:String str = new String();//char[] value = new char[0];String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建了一个长度是16的数组。System.out.println(sb1.length());//sb1.append('a');//value[0] = 'a';sb1.append('b');//value[1] = 'b';StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];//问题1. System.out.println(sb2.length());//3//问题2. 扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。默认情况下,扩容为原来容量的2倍 + 2,同时将原有数组中的元素复制到新的数组中。指导意义:开发中建议大家使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)*/@Testpublic void test1(){StringBuffer sb1 = new StringBuffer("abc");sb1.setCharAt(0,'m');System.out.println(sb1);StringBuffer sb2 = new StringBuffer();System.out.println(sb2.length());//0}/*对比String、StringBuffer、StringBuilder三者的效率:从高到低排列:StringBuilder > StringBuffer > String*/@Testpublic void test3(){//初始设置long startTime = 0L;long endTime = 0L;String text = "";StringBuffer buffer = new StringBuffer("");StringBuilder builder = new StringBuilder("");//开始对比startTime = System.currentTimeMillis();for (int i = 0; i < 20000; i++) {buffer.append(String.valueOf(i));}endTime = System.currentTimeMillis();System.out.println("StringBuffer的执行时间:" + (endTime - startTime));startTime = System.currentTimeMillis();for (int i = 0; i < 20000; i++) {builder.append(String.valueOf(i));}endTime = System.currentTimeMillis();System.out.println("StringBuilder的执行时间:" + (endTime - startTime));startTime = System.currentTimeMillis();for (int i = 0; i < 20000; i++) {text = text + i;}endTime = System.currentTimeMillis();System.out.println("String的执行时间:" + (endTime - startTime));}
Comparable & Comparator
- class Goods implements Comparable
- Arrays.sort(arr,new Comparator(){….}) ```java package com.atguigu.java;
import org.junit.Test;
import java.util.Arrays; import java.util.Comparator;
/**
- 一、说明:Java中的对象,正常情况下,只能进行比较:== 或 != 。不能使用 > 或 < 的
- 但是在开发场景中,我们需要对多个对象进行排序,言外之意,就需要比较对象的大小。
- 如何实现?使用两个接口中的任何一个:Comparable 或 Comparator *
- 二、Comparable接口与Comparator的使用的对比:
- Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小。
- Comparator接口属于临时性的比较。 *thor shkstart
@create 2019 下午 4:41 / public class CompareTest { / Comparable接口的使用举例: 自然排序 1.像String、包装类等实现了Comparable接口,重写了compareTo(obj)方法,给出了比较两个对象大小的方式。 2.像String、包装类重写compareTo()方法以后,进行了从小到大的排列
- 重写compareTo(obj)的规则: 如果当前对象this大于形参对象obj,则返回正整数, 如果当前对象this小于形参对象obj,则返回负整数, 如果当前对象this等于形参对象obj,则返回零。
对于自定义类来说,如果需要排序,我们可以让自定义类实现Comparable接口,重写compareTo(obj)方法。 在compareTo(obj)方法中指明如何排序 */ @Test public void test1(){ String[] arr = new String[]{“AA”,”CC”,”KK”,”MM”,”GG”,”JJ”,”DD”}; // Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
// Comparable接口 demo @Test public void test2(){ Goods[] arr = new Goods[5]; arr[0] = new Goods(“lenovoMouse”,34); arr[1] = new Goods(“dellMouse”,43); arr[2] = new Goods(“xiaomiMouse”,12); arr[3] = new Goods(“huaweiMouse”,65); arr[4] = new Goods(“microsoftMouse”,43);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); }
/* Comparator接口的使用:定制排序 1.背景: 当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码, 或者实现了java.lang.Comparable接口的排序规则不适合当前的操作, 那么可以考虑使用 Comparator 的对象来排序 2.重写compare(Object o1,Object o2)方法,比较o1和o2的大小: 如果方法返回正整数,则表示o1大于o2; 如果返回0,表示相等; 返回负整数,表示o1小于o2。
*/ @Test public void test3(){ String[] arr = new String[]{“AA”,”CC”,”KK”,”MM”,”GG”,”JJ”,”DD”}; Arrays.sort(arr,new Comparator(){
//按照字符串从大到小的顺序排列@Overridepublic int compare(Object o1, Object o2) {if(o1 instanceof String && o2 instanceof String){String s1 = (String) o1;String s2 = (String) o2;return -s1.compareTo(s2);}
// return 0;
throw new RuntimeException("输入的数据类型不一致");}
}); System.out.println(Arrays.toString(arr)); }
@Test public void test4(){ Goods[] arr = new Goods[6]; arr[0] = new Goods(“lenovoMouse”,34); arr[1] = new Goods(“dellMouse”,43); arr[2] = new Goods(“xiaomiMouse”,12); arr[3] = new Goods(“huaweiMouse”,65); arr[4] = new Goods(“huaweiMouse”,224); arr[5] = new Goods(“microsoftMouse”,43);
Arrays.sort(arr, new Comparator() {
//指明商品比较大小的方式:按照产品名称从低到高排序,再按照价格从高到低排序@Overridepublic int compare(Object o1, Object o2) {if(o1 instanceof Goods && o2 instanceof Goods){Goods g1 = (Goods)o1;Goods g2 = (Goods)o2;if(g1.getName().equals(g2.getName())){return -Double.compare(g1.getPrice(),g2.getPrice());}else{return g1.getName().compareTo(g2.getName());}}throw new RuntimeException("输入的数据类型不一致");}
});
System.out.println(Arrays.toString(arr)); }
}
/**
- 商品类 (Comparable接口)
- @author shkstart
@create 2019 下午 4:52 */ public class Goods implements Comparable{
private String name; private double price;
//指明商品比较大小的方式:按照价格从低到高排序,再按照产品名称从高到低排序 @Override public int compareTo(Object o) { // System.out.println(“**“);
if(o instanceof Goods){Goods goods = (Goods)o;//方式一:if(this.price > goods.price){return 1;}else if(this.price < goods.price){return -1;}else{
// return 0;
return -this.name.compareTo(goods.name);}//方式二:
// return Double.compare(this.price,goods.price);
}
// return 0;
throw new RuntimeException("传入的数据类型不一致!");
} }
<a name="jblT2"></a>#### Enum方式一:jdk5.0之前,自定义枚举类```javapackage com.atguigu.java;/*** 一、枚举类的使用* 1.枚举类的理解:类的对象只有有限个,确定的。我们称此类为枚举类* 2.当需要定义一组常量时,强烈建议使用枚举类* 3.如果枚举类中只有一个对象,则可以作为单例模式的实现方式。** 二、如何定义枚举类* 方式一:jdk5.0之前,自定义枚举类* 方式二:jdk5.0,可以使用enum关键字定义枚举类** 三、Enum类中的常用方法:* values()方法:返回枚举类型的对象数组。该方法可以很方便地遍历所有的枚举值。* valueOf(String str):可以把一个字符串转为对应的枚举类对象。要求字符串必须是枚举类对象的“名字”。如不是,会有运行时异常:IllegalArgumentException。* toString():返回当前枚举类对象常量的名称** 四、使用enum关键字定义的枚举类实现接口的情况* 情况一:实现接口,在enum类中实现抽象方法* 情况二:让枚举类的对象分别实现接口中的抽象方法** @author shkstart* @create 2019 上午 10:17*/public class SeasonTest {public static void main(String[] args) {Season spring = Season.SPRING;System.out.println(spring);}}//自定义枚举类class Season{//1.声明Season对象的属性:private final修饰private final String seasonName;private final String seasonDesc;//2.私有化类的构造器,并给对象属性赋值private Season(String seasonName,String seasonDesc){this.seasonName = seasonName;this.seasonDesc = seasonDesc;}//3.提供当前枚举类的多个对象:public static final的public static final Season SPRING = new Season("春天","春暖花开");public static final Season SUMMER = new Season("夏天","夏日炎炎");public static final Season AUTUMN = new Season("秋天","秋高气爽");public static final Season WINTER = new Season("冬天","冰天雪地");//4.其他诉求1:获取枚举类对象的属性public String getSeasonName() {return seasonName;}public String getSeasonDesc() {return seasonDesc;}//4.其他诉求1:提供toString()@Overridepublic String toString() {return "Season{" +"seasonName='" + seasonName + '\'' +", seasonDesc='" + seasonDesc + '\'' +'}';}}
方式二:jdk5.0,可以使用enum关键字定义枚举类
package com.atguigu.java;/*** 使用enum关键字定义枚举类* 说明:定义的枚举类默认继承于java.lang.Enum类** @author shkstart* @create 2019 上午 10:35*/public class SeasonTest1 {public static void main(String[] args) {Season1 summer = Season1.SUMMER;//toString():返回枚举类对象的名称System.out.println(summer.toString());// System.out.println(Season1.class.getSuperclass());System.out.println("****************");//values():返回所有的枚举类对象构成的数组Season1[] values = Season1.values();for(int i = 0;i < values.length;i++){System.out.println(values[i]);values[i].show();}System.out.println("****************");Thread.State[] values1 = Thread.State.values();for (int i = 0; i < values1.length; i++) {System.out.println(values1[i]);}//valueOf(String objName):返回枚举类中对象名是objName的对象。Season1 winter = Season1.valueOf("WINTER");//如果没有objName的枚举类对象,则抛异常:IllegalArgumentException// Season1 winter = Season1.valueOf("WINTER1");System.out.println(winter);winter.show();}}interface Info{void show();}//使用enum关键字枚举类enum Season1 implements Info{//1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象";"结束SPRING("春天","春暖花开"){@Overridepublic void show() {System.out.println("春天在哪里?");}},SUMMER("夏天","夏日炎炎"){@Overridepublic void show() {System.out.println("宁夏");}},AUTUMN("秋天","秋高气爽"){@Overridepublic void show() {System.out.println("秋天不回来");}},WINTER("冬天","冰天雪地"){@Overridepublic void show() {System.out.println("大约在冬季");}};//2.声明Season对象的属性:private final修饰private final String seasonName;private final String seasonDesc;//2.私有化类的构造器,并给对象属性赋值private Season1(String seasonName,String seasonDesc){this.seasonName = seasonName;this.seasonDesc = seasonDesc;}//4.其他诉求1:获取枚举类对象的属性public String getSeasonName() {return seasonName;}public String getSeasonDesc() {return seasonDesc;}// //4.其他诉求1:提供toString()//// @Override// public String toString() {// return "Season1{" +// "seasonName='" + seasonName + '\'' +// ", seasonDesc='" + seasonDesc + '\'' +// '}';// }// @Override// public void show() {// System.out.println("这是一个季节");// }}
集合框架
Collection
//8.集合 --->数组:toArray()Object[] arr = coll.toArray();for(int i = 0;i < arr.length;i++){System.out.println(arr[i]);}//拓展:数组 --->集合:调用Arrays类的静态方法asList()List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});System.out.println(list);
List
Set

Map

反射 & 动态代理
day11
Lambda
基本使用
/*** Lambda表达式的使用** 1.举例: (o1,o2) -> Integer.compare(o1,o2);* 2.格式:* -> :lambda操作符 或 箭头操作符* ->左边:lambda形参列表 (其实就是接口中的抽象方法的形参列表)* ->右边:lambda体 (其实就是重写的抽象方法的方法体)** 3. Lambda表达式的使用:(分为6种情况介绍)** 总结:* ->左边:lambda形参列表的参数类型可以省略(类型推断);如果lambda形参列表只有一个参数,其一对()也可以省略* ->右边:lambda体应该使用一对{}包裹;如果lambda体只有一条执行语句(可能是return语句),省略这一对{}和return关键字** 4.Lambda表达式的本质:作为函数式接口的实例** 5. 如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口。我们可以在一个接口上使用 @FunctionalInterface 注解,* 这样做可以检查它是否是一个函数式接口。** 6. 所以以前用匿名实现类表示的现在都可以用Lambda表达式来写。** @author shkstart* @create 2019 上午 11:40*/public class LambdaTest1 {//语法格式一:无参,无返回值@Testpublic void test1(){Runnable r1 = new Runnable() {@Overridepublic void run() {System.out.println("我爱北京天安门");}};r1.run();System.out.println("***********************");Runnable r2 = () -> {System.out.println("我爱北京故宫");};r2.run();}//语法格式二:Lambda 需要一个参数,但是没有返回值。@Testpublic void test2(){Consumer<String> con = new Consumer<String>() {@Overridepublic void accept(String s) {System.out.println(s);}};con.accept("谎言和誓言的区别是什么?");System.out.println("*******************");Consumer<String> con1 = (String s) -> {System.out.println(s);};con1.accept("一个是听得人当真了,一个是说的人当真了");}//语法格式三:数据类型可以省略,因为可由编译器推断得出,称为“类型推断”@Testpublic void test3(){Consumer<String> con1 = (String s) -> {System.out.println(s);};con1.accept("一个是听得人当真了,一个是说的人当真了");System.out.println("*******************");Consumer<String> con2 = (s) -> {System.out.println(s);};con2.accept("一个是听得人当真了,一个是说的人当真了");}@Testpublic void test4(){ArrayList<String> list = new ArrayList<>();//类型推断int[] arr = {1,2,3};//类型推断}//语法格式四:Lambda 若只需要一个参数时,参数的小括号可以省略@Testpublic void test5(){Consumer<String> con1 = (s) -> {System.out.println(s);};con1.accept("一个是听得人当真了,一个是说的人当真了");System.out.println("*******************");Consumer<String> con2 = s -> {System.out.println(s);};con2.accept("一个是听得人当真了,一个是说的人当真了");}//语法格式五:Lambda 需要两个或以上的参数,多条执行语句,并且可以有返回值@Testpublic void test6(){Comparator<Integer> com1 = new Comparator<Integer>() {@Overridepublic int compare(Integer o1, Integer o2) {System.out.println(o1);System.out.println(o2);return o1.compareTo(o2);}};System.out.println(com1.compare(12,21));System.out.println("*****************************");Comparator<Integer> com2 = (o1,o2) -> {System.out.println(o1);System.out.println(o2);return o1.compareTo(o2);};System.out.println(com2.compare(12,6));}//语法格式六:当 Lambda 体只有一条语句时,return 与大括号若有,都可以省略@Testpublic void test7(){Comparator<Integer> com1 = (o1,o2) -> {return o1.compareTo(o2);};System.out.println(com1.compare(12,6));System.out.println("*****************************");Comparator<Integer> com2 = (o1,o2) -> o1.compareTo(o2);System.out.println(com2.compare(12,21));}@Testpublic void test8(){Consumer<String> con1 = s -> {System.out.println(s);};con1.accept("一个是听得人当真了,一个是说的人当真了");System.out.println("*****************************");Consumer<String> con2 = s -> System.out.println(s);con2.accept("一个是听得人当真了,一个是说的人当真了");}
方法引用
/*** 方法引用的使用** 1.使用情境:当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用!** 2.方法引用,本质上就是Lambda表达式,而Lambda表达式作为函数式接口的实例。所以* 方法引用,也是函数式接口的实例。** 3. 使用格式: 类(或对象) :: 方法名** 4. 具体分为如下的三种情况:* 情况1 对象 :: 非静态方法* 情况2 类 :: 静态方法** 情况3 类 :: 非静态方法** 5. 方法引用使用的要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的* 形参列表和返回值类型相同!(针对于情况1和情况2)** Created by shkstart.*/public class MethodRefTest {// 情况一:对象 :: 实例方法//Consumer中的void accept(T t)//PrintStream中的void println(T t)@Testpublic void test1() {Consumer<String> con1 = str -> System.out.println(str);con1.accept("北京");System.out.println("*******************");PrintStream ps = System.out;Consumer<String> con2 = ps::println;con2.accept("beijing");}//Supplier中的T get()//Employee中的String getName()@Testpublic void test2() {Employee emp = new Employee(1001,"Tom",23,5600);Supplier<String> sup1 = () -> emp.getName();System.out.println(sup1.get());System.out.println("*******************");Supplier<String> sup2 = emp::getName;System.out.println(sup2.get());}// 情况二:类 :: 静态方法//Comparator中的int compare(T t1,T t2)//Integer中的int compare(T t1,T t2)@Testpublic void test3() {Comparator<Integer> com1 = (t1,t2) -> Integer.compare(t1,t2);System.out.println(com1.compare(12,21));System.out.println("*******************");Comparator<Integer> com2 = Integer::compare;System.out.println(com2.compare(12,3));}//Function中的R apply(T t)//Math中的Long round(Double d)@Testpublic void test4() {Function<Double,Long> func = new Function<Double, Long>() {@Overridepublic Long apply(Double d) {return Math.round(d);}};System.out.println("*******************");Function<Double,Long> func1 = d -> Math.round(d);System.out.println(func1.apply(12.3));System.out.println("*******************");Function<Double,Long> func2 = Math::round;System.out.println(func2.apply(12.6));}// 情况三:类 :: 实例方法 (有难度)// Comparator中的int comapre(T t1,T t2)// String中的int t1.compareTo(t2)@Testpublic void test5() {Comparator<String> com1 = (s1,s2) -> s1.compareTo(s2);System.out.println(com1.compare("abc","abd"));System.out.println("*******************");Comparator<String> com2 = String :: compareTo;System.out.println(com2.compare("abd","abm"));}//BiPredicate中的boolean test(T t1, T t2);//String中的boolean t1.equals(t2)@Testpublic void test6() {BiPredicate<String,String> pre1 = (s1,s2) -> s1.equals(s2);System.out.println(pre1.test("abc","abc"));System.out.println("*******************");BiPredicate<String,String> pre2 = String :: equals;System.out.println(pre2.test("abc","abd"));}// Function中的R apply(T t)// Employee中的String getName();@Testpublic void test7() {Employee employee = new Employee(1001, "Jerry", 23, 6000);Function<Employee,String> func1 = e -> e.getName();System.out.println(func1.apply(employee));System.out.println("*******************");Function<Employee,String> func2 = Employee::getName;System.out.println(func2.apply(employee));}}
java内置的4大核心函数式接口
package com.atguigu.java1;import org.junit.Test;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.function.Consumer;import java.util.function.Predicate;/*** java内置的4大核心函数式接口** 消费型接口 Consumer<T> void accept(T t)* 供给型接口 Supplier<T> T get()* 函数型接口 Function<T,R> R apply(T t)* 断定型接口 Predicate<T> boolean test(T t)*/public class LambdaTest2 {@Testpublic void test1(){happyTime(500, new Consumer<Double>() {@Overridepublic void accept(Double aDouble) {System.out.println("学习太累了,去天上人间买了瓶矿泉水,价格为:" + aDouble);}});System.out.println("********************");happyTime(400,money -> System.out.println("学习太累了,去天上人间喝了口水,价格为:" + money));}public void happyTime(double money, Consumer<Double> con){con.accept(money);}@Testpublic void test2(){List<String> list = Arrays.asList("北京","南京","天津","东京","西京","普京");List<String> filterStrs = filterString(list, new Predicate<String>() {@Overridepublic boolean test(String s) {return s.contains("京");}});System.out.println(filterStrs);List<String> filterStrs1 = filterString(list,s -> s.contains("京"));System.out.println(filterStrs1);}//根据给定的规则,过滤集合中的字符串。此规则由Predicate的方法决定public List<String> filterString(List<String> list, Predicate<String> pre){ArrayList<String> filterList = new ArrayList<>();for(String s : list){if(pre.test(s)){filterList.add(s);}}return filterList;}}
StreamAPI
package com.atguigu.java3;import com.atguigu.java2.Employee;import com.atguigu.java2.EmployeeData;import org.junit.Test;import java.util.Arrays;import java.util.List;import java.util.stream.IntStream;import java.util.stream.Stream;/*** 1. Stream关注的是对数据的运算,与CPU打交道* 集合关注的是数据的存储,与内存打交道** 2.* ①Stream 自己不会存储元素。* ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。* ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行** 3.Stream 执行流程* ① Stream的实例化* ② 一系列的中间操作(过滤、映射、...)* ③ 终止操作** 4.说明:* 4.1 一个中间操作链,对数据源的数据进行处理* 4.2 一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用*** 测试Stream的实例化** @author shkstart* @create 2019 下午 4:25*/public class StreamAPITest {//创建 Stream方式一:通过集合@Testpublic void test1(){List<Employee> employees = EmployeeData.getEmployees();// default Stream<E> stream() : 返回一个顺序流Stream<Employee> stream = employees.stream();// default Stream<E> parallelStream() : 返回一个并行流Stream<Employee> parallelStream = employees.parallelStream();}//创建 Stream方式二:通过数组@Testpublic void test2(){int[] arr = new int[]{1,2,3,4,5,6};//调用Arrays类的static <T> Stream<T> stream(T[] array): 返回一个流IntStream stream = Arrays.stream(arr);Employee e1 = new Employee(1001,"Tom");Employee e2 = new Employee(1002,"Jerry");Employee[] arr1 = new Employee[]{e1,e2};Stream<Employee> stream1 = Arrays.stream(arr1);}//创建 Stream方式三:通过Stream的of()@Testpublic void test3(){Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);}//创建 Stream方式四:创建无限流@Testpublic void test4(){// 迭代// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)//遍历前10个偶数Stream.iterate(0, t -> t + 2).limit(10).forEach(System.out::println);// 生成// public static<T> Stream<T> generate(Supplier<T> s)Stream.generate(Math::random).limit(10).forEach(System.out::println);}}------------------------------------------------------------------------------package com.atguigu.java3;import com.atguigu.java2.Employee;import com.atguigu.java2.EmployeeData;import org.junit.Test;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.stream.Stream;/*** 测试Stream的中间操作*/public class StreamAPITest1 {//1-筛选与切片@Testpublic void test1(){List<Employee> list = EmployeeData.getEmployees();// filter(Predicate p)——接收 Lambda , 从流中排除某些元素。Stream<Employee> stream = list.stream();//练习:查询员工表中薪资大于7000的员工信息stream.filter(e -> e.getSalary() > 7000).forEach(System.out::println);System.out.println();// limit(n)——截断流,使其元素不超过给定数量。list.stream().limit(3).forEach(System.out::println);System.out.println();// skip(n) —— 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补list.stream().skip(3).forEach(System.out::println);System.out.println();// distinct()——筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素list.add(new Employee(1010,"刘强东",40,8000));list.add(new Employee(1010,"刘强东",41,8000));list.add(new Employee(1010,"刘强东",40,8000));list.add(new Employee(1010,"刘强东",40,8000));list.add(new Employee(1010,"刘强东",40,8000));// System.out.println(list);list.stream().distinct().forEach(System.out::println);}//映射@Testpublic void test2(){// map(Function f)——接收一个函数作为参数,将元素转换成其他形式或提取信息,该函数会被应用到每个元素上,并将其映射成一个新的元素。List<String> list = Arrays.asList("aa", "bb", "cc", "dd");list.stream().map(str -> str.toUpperCase()).forEach(System.out::println);// 练习1:获取员工姓名长度大于3的员工的姓名。List<Employee> employees = EmployeeData.getEmployees();Stream<String> namesStream = employees.stream().map(Employee::getName);namesStream.filter(name -> name.length() > 3).forEach(System.out::println);System.out.println();//练习2:Stream<Stream<Character>> streamStream = list.stream().map(StreamAPITest1::fromStringToStream);streamStream.forEach(s ->{s.forEach(System.out::println);});System.out.println();// flatMap(Function f)——接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。Stream<Character> characterStream = list.stream().flatMap(StreamAPITest1::fromStringToStream);characterStream.forEach(System.out::println);}//将字符串中的多个字符构成的集合转换为对应的Stream的实例public static Stream<Character> fromStringToStream(String str){//aaArrayList<Character> list = new ArrayList<>();for(Character c : str.toCharArray()){list.add(c);}return list.stream();}@Testpublic void test3(){ArrayList list1 = new ArrayList();list1.add(1);list1.add(2);list1.add(3);ArrayList list2 = new ArrayList();list2.add(4);list2.add(5);list2.add(6);// list1.add(list2);list1.addAll(list2);System.out.println(list1);}//3-排序@Testpublic void test4(){// sorted()——自然排序List<Integer> list = Arrays.asList(12, 43, 65, 34, 87, 0, -98, 7);list.stream().sorted().forEach(System.out::println);//抛异常,原因:Employee没有实现Comparable接口// List<Employee> employees = EmployeeData.getEmployees();// employees.stream().sorted().forEach(System.out::println);// sorted(Comparator com)——定制排序List<Employee> employees = EmployeeData.getEmployees();employees.stream().sorted( (e1,e2) -> {int ageValue = Integer.compare(e1.getAge(),e2.getAge());if(ageValue != 0){return ageValue;}else{return -Double.compare(e1.getSalary(),e2.getSalary());}}).forEach(System.out::println);}}------------------------------------------------------------------------package com.atguigu.java3;import com.atguigu.java2.Employee;import com.atguigu.java2.EmployeeData;import org.junit.Test;import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream;/*** 测试Stream的终止操作** @author shkstart* @create 2019 下午 6:37*/public class StreamAPITest2 {//1-匹配与查找@Testpublic void test1(){List<Employee> employees = EmployeeData.getEmployees();// allMatch(Predicate p)——检查是否匹配所有元素。// 练习:是否所有的员工的年龄都大于18boolean allMatch = employees.stream().allMatch(e -> e.getAge() > 18);System.out.println(allMatch);// anyMatch(Predicate p)——检查是否至少匹配一个元素。// 练习:是否存在员工的工资大于 10000boolean anyMatch = employees.stream().anyMatch(e -> e.getSalary() > 10000);System.out.println(anyMatch);// noneMatch(Predicate p)——检查是否没有匹配的元素。// 练习:是否存在员工姓“雷”boolean noneMatch = employees.stream().noneMatch(e -> e.getName().startsWith("雷"));System.out.println(noneMatch);// findFirst——返回第一个元素Optional<Employee> employee = employees.stream().findFirst();System.out.println(employee);// findAny——返回当前流中的任意元素Optional<Employee> employee1 = employees.parallelStream().findAny();System.out.println(employee1);}@Testpublic void test2(){List<Employee> employees = EmployeeData.getEmployees();// count——返回流中元素的总个数long count = employees.stream().filter(e -> e.getSalary() > 5000).count();System.out.println(count);// max(Comparator c)——返回流中最大值// 练习:返回最高的工资:Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());Optional<Double> maxSalary = salaryStream.max(Double::compare);System.out.println(maxSalary);// min(Comparator c)——返回流中最小值// 练习:返回最低工资的员工Optional<Employee> employee = employees.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));System.out.println(employee);System.out.println();// forEach(Consumer c)——内部迭代employees.stream().forEach(System.out::println);//使用集合的遍历操作employees.forEach(System.out::println);}//2-归约@Testpublic void test3(){// reduce(T identity, BinaryOperator)——可以将流中元素反复结合起来,得到一个值。返回 T// 练习1:计算1-10的自然数的和List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);Integer sum = list.stream().reduce(0, Integer::sum);System.out.println(sum);// reduce(BinaryOperator) ——可以将流中元素反复结合起来,得到一个值。返回 Optional<T>// 练习2:计算公司所有员工工资的总和List<Employee> employees = EmployeeData.getEmployees();Stream<Double> salaryStream = employees.stream().map(Employee::getSalary);// Optional<Double> sumMoney = salaryStream.reduce(Double::sum);Optional<Double> sumMoney = salaryStream.reduce((d1,d2) -> d1 + d2);System.out.println(sumMoney.get());}//3-收集@Testpublic void test4(){// collect(Collector c)——将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法// 练习1:查找工资大于6000的员工,结果返回为一个List或SetList<Employee> employees = EmployeeData.getEmployees();List<Employee> employeeList = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toList());employeeList.forEach(System.out::println);System.out.println();Set<Employee> employeeSet = employees.stream().filter(e -> e.getSalary() > 6000).collect(Collectors.toSet());employeeSet.forEach(System.out::println);}}
