Comparable 重写 compareTo两个参数报错—排序
public class ComparatorDemo {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<>();
arr.add("aaa");
arr.add("bb");
arr.add("cccc");
arr.add("d");
System.out.println(arr);
//Collections.sort(arr,getComparator());
System.out.println(arr);
}
private static Comparable<String> getComparator(){
// return new Comparable<String>() {
// @Override
// public int compareTo(String s2,String s1) {
// return s2.length()-s1.length();
// }
// };
//不知道为啥报错,它不允许两个参数
return (s1,s2) -> s1.length()-s2.length();
}
}
Supplier函数式接口
import java.util.function.Supplier;
public class SupplierDemo {
public static void main(String[] args) {
String s = getString(() -> "柳夜熙") ;
System.out.println(s);
//>>>柳夜熙
Integer i = getInteger(()->80);
System.out.println(i);
//>>>80
}
private static String getString(Supplier<String> s) {
return s.get();
}
private static Integer getInteger(Supplier<Integer> s) {
return s.get();
}
}
import java.util.function.Supplier;
public class SuplierTest {
public static void main(String[] args) {
int[] arr = {88, 1, 2, 3, 5, 8, 13, 21, 34};
int Max = getMax(() -> {
int max = arr[0];
for (int i : arr) {
if (i > max) {
max = i;
}
}
return max;
});
System.out.println(Max);
}
private static int getMax(Supplier<Integer> sup) {
return sup.get();
}
}
Consumer函数式接口
import java.util.function.Consumer;
public class ConsumerDemo {
public static void main(String[] args) {
operatorString("柳夜熙", s -> System.out.println(s));
operatorString("青染", System.out::println);
operatorString("反着读", s -> System.out.println(new StringBuilder(s).reverse().toString()));
operatorString("牙刷", s -> System.out.println(s), s -> System.out.println(new StringBuilder(s).reverse().toString()));
}
private static void operatorString(String name, Consumer<String> con) {
con.accept(name);
}
private static void operatorString(String name, Consumer<String> con1, Consumer<String> con2) {
/* 方式一:
con1.accept(name);
con2.accept(name);
*/
//方式二:
con1.andThen(con2).accept(name);
/* 源码 andThen
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
*/
}
}
import java.util.function.Consumer;
public class ConsumerTest {
public static void main(String[] args) {
String[] strArr = {"张飞,35", "武则天,28", "孙悟空,500"};
printInfo(strArr, s -> {
String name = s.split(",")[0];
System.out.print(name);
}, s -> {
Integer age = Integer.parseInt(s.split(",")[1]);
System.out.println(age);
});
}
//>>> 张飞35
// 武则天28
// 孙悟空500
private static void printInfo(String[] strArr, Consumer<String> con1, Consumer<String> con2) {
for (String s : strArr) {
con1.andThen(con2).accept(s);
}
}
}
Predicate函数式接口
import java.util.function.Predicate;
public class PredicateDemo {
public static void main(String[] args) {
Boolean b1 = checkString("Hello", s -> s.length() > 8);
System.out.println(b1);
//>>> false
Boolean b2 = checkString("Hello", s -> s.length() < 8);
System.out.println(b2);
//>>> true
boolean b3 = checkString("world", s -> s.length() > 5, s -> s.length() < 5);
System.out.println(b3);
//>>> false
}
private static boolean checkString(String s, Predicate<String> pre1,Predicate<String> pre2) {
/*boolean b1 = pre1.test(s);
boolean b2 = pre2.test(s);
boolean b = b1 && b2;
return b;*/
//return pre1.and(pre2).test(s); //逻辑与
return pre1.or(pre2).test(s); //逻辑或
/**
* default Predicate<T> or(Predicate<? super T> other) {
* Objects.requireNonNull(other);
* return (t) -> test(t) || other.test(t);
* }
*/
}
private static boolean checkString(String s, Predicate<String> pre) {
//return pre.test(s);
//取反
//return !pre.test(s);
return pre.negate().test(s); //逻辑非
/*
default Predicate<T> negate() {
return (t) -> !test(t);
}
*/
}
}
predicate条件筛选
import java.util.ArrayList;
import java.util.function.Predicate;
/**
* 条件筛选 --> 名字长度大于2,年龄大于30
*/
public class PredicateTest {
public static void main(String[] args) {
String[] strArr = {"张伟,40", "曾小贤,38", "胡一菲,28", "唐悠悠,25"};
ArrayList<String> arr = myFilter(strArr, s -> s.split(",")[0].length() > 2, s -> Integer.parseInt(s.split(",")[1]) > 30);
System.out.println(arr);
//>>> [曾小贤,38]
}
private static ArrayList<String> myFilter(String[] strArr, Predicate<String> pre1, Predicate<String> pre2) {
ArrayList<String> arr = new ArrayList<>();
for (String s : strArr) {
if (pre1.and(pre2).test(s)) {
arr.add(s);
}
}
return arr;
}
}
Function函数式接口
import java.util.function.Function;
public class FunctionDemo {
public static void main(String[] args) {
convert("100", s -> Integer.parseInt(s));
convert("100", Integer::parseInt);
convert(888, i -> i.toString());
convert(888, i -> String.valueOf(i + 666));
convert("2", s -> Integer.parseInt(s) * 10, i -> i.toString());
}
//字符串转int类型
private static void convert(String s, Function<String, Integer> func) {
Integer i = func.apply(s);
System.out.println(i);
//>>> 100
// 100
}
//int转字符串
private static void convert(int i, Function<Integer, String> func) {
String s = func.apply(i);
System.out.println(s);
//>>> 888
// 1554
}
//字符串转int类型,做乘法后,再转字符串
private static void convert(String s, Function<String, Integer> func1, Function<Integer, String> func2) {
Integer i = func1.apply(s);
String ss = func2.apply(i);
System.out.println(ss);
//>>> 20
//方式二
String ss1 = func1.andThen(func2).apply(s);
System.out.println(ss1);
//>>> 20
/**
* default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
* Objects.requireNonNull(after);
* return (T t) -> after.apply(apply(t));
* }
*/
}
}
import java.util.function.Function;
public class FunctionTest {
public static void main(String[] args) {
useFunction("租八戒,300",s -> Integer.parseInt(s.split(",")[1])+700,i -> new StringBuilder("租八戒,").append(i).toString());
}
private static void useFunction(String s, Function<String,Integer> fun1,Function<Integer,String> fun2) {
String ss = fun1.andThen(fun2).apply(s);
System.out.println(ss);
//>>> 租八戒,1000
}
}
Stream流
普通方式
import java.util.ArrayList;
public class StreamDemo {
public static void main(String[] args) {
String[] strArr = {"张国荣", "张伟", "李张洋", "张飞", "王红", "张三", "张惠妹"};
ArrayList<String> arrZ = new ArrayList<>(); //筛选姓张的
for (String s : strArr) {
// if (s.substring(0,1).equals("张")){
// arrZ.add(s);
// }
if (s.startsWith("张")){
arrZ.add(s);
}
}
System.out.println(arrZ);
ArrayList<String> arrZ3 = new ArrayList<>();
for (String s: arrZ){
if (s.length()>2){
arrZ3.add(s);
}
}
System.out.println(arrZ3);
}
}
使用Stream流
public class StreamTest {
public static void main(String[] args) {
ArrayList<String> strArr = new ArrayList<>();
//String[] strArr = {"张国荣", "张伟", "李张洋", "张飞", "王红", "张三", "张惠妹"};
strArr.add("张国荣");
strArr.add("张伟");
strArr.add("李张洋");
strArr.add("张飞");
strArr.add("王红");
strArr.add("张三");
strArr.add("张惠妹");
strArr.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(s -> System.out.println(s));
System.out.println("----");
strArr.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(System.out::println);
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Stream;
public class StreamTest {
public static void main(String[] args) {
//Collections 体系 直接生成
ArrayList<String> strArr = new ArrayList<>();
strArr.add("张国荣");
strArr.add("张伟");
strArr.add("李张洋");
strArr.add("张飞");
strArr.add("王红");
strArr.add("张三");
strArr.add("张惠妹");
strArr.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(s -> System.out.println(s));
System.out.println("----");
strArr.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(System.out::println);
System.out.println("----");
//数组
String[] strArr1 = {"张国荣", "张伟", "李张洋", "张飞", "王红", "张三", "张惠妹"};
Stream.of(strArr1).filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(System.out::println);
//Map体系集合 间接生成流
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "张国荣");
map.put(2, "张伟");
map.put(3, "李张洋");
map.put(4, "张飞");
map.put(5, "王红");
map.put(6, "张三");
map.put(7, "张惠妹");
//map.keySet().stream().filter(i -> i>3).forEach(System.out::println);
map.values().stream().filter(s -> s.startsWith("张")).filter(s -> s.length() > 2).forEach(System.out::println);
}
}
Stream 方法
import java.util.ArrayList;
import java.util.stream.Stream;
public class StreamDemo01 {
public static void main(String[] args) {
ArrayList<String> strArr = new ArrayList<>();
strArr.add("张国荣");
strArr.add("张伟");
strArr.add("李张洋");
strArr.add("张飞");
strArr.add("王红");
strArr.add("张三");
strArr.add("张惠妹");
//取 前5个元素
Stream<String> limit = strArr.stream().limit(5);
//limit.forEach(System.out::println);
//跳过 前2个元素
Stream<String> skip = strArr.stream().skip(2);
//skip.forEach(System.out::println);
System.out.println("----");
//concat 连接两个流
//Stream.concat(limit, skip).forEach(System.out::println);
//>>> 抛出异常:stream has already been operated upon or closed
//原因 : 前方的limit和skip流 已使用了forEach关闭.
//distinct 去重
Stream.concat(limit, skip).distinct().forEach(System.out::println);
//int[] arr = {7, 5, 9, 2, 6, 3, 5, 1, 2, 8, 4}; -->
// Redundant 'sorted' call: stream contains at most one element
Integer[] arr = {7, 5, 9, 2, 6, 3, 5, 1, 8, 4};
Stream.of(arr).sorted().forEach(System.out::print);
System.out.println();
String[] sarr = {"b", "d", "c", "f", "a", "e", "g"};
Stream.of(sarr).sorted().forEach(System.out::print);
System.out.println();
Stream.of(sarr).map(s -> stringToAscii(s)).forEach(s -> System.out.print(s+"+"));
//求和
int sum = Stream.of(sarr).map(s -> stringToAscii(s)).mapToInt(Integer::parseInt).sum();
System.out.println("\n"+sum);
//统计个数
long count = Stream.of(sarr).count();
System.out.println(count);
}
/**
* 字符串转换为Ascii
*
* @param value
* @return
*/
public static String stringToAscii(String value) {
StringBuffer sbu = new StringBuffer();
char[] chars = value.toCharArray();
for (int i = 0; i < chars.length; i++) {
if (i != chars.length - 1) {
sbu.append((int) chars[i]).append(",");
} else {
sbu.append((int) chars[i]);
}
}
return sbu.toString();
}
}
Stream收集操作
类加载
public class ClassloaderDemo {
public static void main(String[] args) {
ClassLoader c = ClassLoader.getSystemClassLoader();
System.out.println(c);
//>>> Launcher$AppClassLoader 系统类加载器
ClassLoader c1 = c.getParent(); //返回父类加载器
System.out.println(c1);
//>>> Launcher$ExtClassLoader 平台类加载器
System.out.println(c1.getParent());
//null 内置类加载器Bootstrap,通常表示为null
}
}
反射
Student
public class Student {
private String name;
int age;
public String address;
public Student() {
}
private Student(String name, String address) {
this.name = name;
this.address = address;
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
private void method1() {
System.out.println("method1");
}
public void method2() {
System.out.println("method2");
}
protected void method3() {
System.out.println("method3");
}
void method4() {
System.out.println("method4");
}
public String method5(String ss) {
return ss;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
反射的三种方式
/**
* 反射的三种方式
*/
public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
/**
* 第一种:最简洁,最方便 .Class
*/
Class<Student> sc = Student.class;
System.out.println(sc);
//>>> class org.itheima_01.Student
Class<Student> sc1 = Student.class;
System.out.println(sc1);
System.out.println(sc==sc1);
/**
* 第二种:通过类方法的 getClass()
*/
Student s = new Student();
Class<? extends Student> sc2 = s.getClass();
System.out.println(sc2);
/**
* 第三种:可配置,最灵活 Class.forName 需抛出ClassNotFoundException异常
*/
Class<?> sc3 = Class.forName("org.itheima_01.Student");
System.out.println(sc3);
}
}
通过反射 获取类构造方法,创建对象
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo01 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取所有的 公共构造方法 getConstructors
Class<?> sc = Class.forName("org.itheima_01.Student");
Constructor<?>[] constructors = sc.getConstructors();
for (Constructor c:constructors){
//System.out.println(c);
}
/*
>>> public org.itheima_01.Student(java.lang.String,int,java.lang.String)
public org.itheima_01.Student()
*/
//获取所有的构造方法 getDeclaredConstructors
Constructor<?>[] dc = sc.getDeclaredConstructors();
for (Constructor c:dc){
//System.out.println(c);
}
/**
* 通过反射创建对象
*/
//公共无参
Constructor<?> con = sc.getConstructor(); //不写参数就是默认的无参构造方法
Object o = con.newInstance();
System.out.println(o);
//私有带参 编译时异常-报错:java.lang.NoSuchMethodException
/*Constructor<?> con1 = sc.getConstructor(String.class, String.class);
Object o1 = con1.newInstance("秦苒", "武汉");
System.out.println(o1);*/
//公共带参
Constructor<?> con2 = sc.getConstructor(String.class,int.class, String.class);
Object o2 = con2.newInstance("秦苒",18, "武汉");
System.out.println(o2);
/**
* 通过new关键字创建对象
*/
//公共无参
Student s = new Student();
System.out.println(s);
//私有带参 运行时异常-报错:'Student(java.lang.String, java.lang.String)' has private access in 'org.itheima_01.Student'
/*Student s1 = new Student("林风","舟山");
System.out.println(s1);*/
//公共带参
Student s2 = new Student("林风",25,"舟山");
System.out.println(s2);
}
}
暴力反射
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo02 {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
Class<?> c = Class.forName("org.itheima_01.Student");
//无法使用私有构造方法 私有报错:IllegalAccessException
Constructor<?> dc = c.getDeclaredConstructor(String.class, int.class, String.class);
Object o = dc.newInstance("陈尽", 21, "长春");
System.out.println(o);
//>>>Student{name='陈尽', age=21, address='长春'}
/**
* 暴力反射 setAccessible - 可访问私有构造方法
*/
Constructor<?> con = c.getDeclaredConstructor(String.class, String.class);
con.setAccessible(true); //取消访问检查
Object o1 = con.newInstance("青岚", "成都");
System.out.println(o1);
//>>> Student{name='青岚', age=0, address='成都'}
}
}
反射获取成员变量
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
public class ReflectDemo03 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("org.itheima_01.Student");
/**
* 获取所有成员变量
*/
Field[] dfs = c.getDeclaredFields();
for (Field f:dfs){
System.out.println(f);
}
Constructor<?> con = c.getConstructor();
Object o = con.newInstance();
/**
* 暴力私有变量访问 name
*/
//方式一通用
Field name = c.getDeclaredField("name");
name.setAccessible(true);
Field address = c.getField("address");
Field age = c.getDeclaredField("age");
name.set(o,"张白亮");
age.set(o,18);
address.set(o,"长寿");
System.out.println(o);
//>>> Student{name='张白亮', age=18, address='长寿'}
}
}
反射获取成员方法
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectDemo04 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("org.itheima_01.Student");
//所有-包括继承的方法
Method[] methods = c.getMethods();
for (Method m:methods){
//System.out.println(m);
}
//获取本类的所有方法,只是本类的
Method[] dms = c.getDeclaredMethods();
for (Method m:dms){
//System.out.println(m);
}
//创建对象
Constructor<?> con = c.getConstructor();
Object o = con.newInstance();
/**
* 调用方法
*/
//private 修饰的需使用setAccessible暴力访问
Method method1 = c.getDeclaredMethod("method1"); //NoSuchMethodException
method1.setAccessible(true);
method1.invoke(o);
//只有public 修饰的才可通过getMethod 访问
Method method2 = c.getMethod("method2"); //NoSuchMethodException
method2.invoke(o);
//protected 修饰
Method method3 = c.getDeclaredMethod("method3"); //NoSuchMethodException
method3.invoke(o);
//默认修饰符
Method method4 = c.getDeclaredMethod("method4"); //NoSuchMethodException
method4.invoke(o);
//带参带返回值 的方法
Method method5 = c.getMethod("method5", String.class);
System.out.println(method5.invoke(o,"带参带返回值"));
String s = (String)method5.invoke(o, "我是参数");
System.out.println(s);
}
}
反射越过泛型检查
/**
* 通过反射越过泛型检查
*/
public class ReflectDemo05 {
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
/**
* 通过反射在ArrayList<Integer>中添加一个字符串
*/
ArrayList<Integer> arr = new ArrayList<>();
//arr.add("字符串");
arr.add(666);
Class<? extends ArrayList> aClass = arr.getClass();
Method add = aClass.getMethod("add", Object.class);
add.invoke(arr,"字符串");
System.out.println(arr);
//>>> [666, 字符串]
}
}
反射读取配置文件
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectDemo06 {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Teacher t = new Teacher();
t.study();
/**
* 通过反射读取配置文件调用函数,灵活性更高
* 配置 类名 与 方法名
* class.txt 文件内容如下:
* ClassName = org.itheima_01.Teacher
* MethodName = study
*/
Properties properties = new Properties();
//Ctrl+Shift+C 复制文件绝对路径
FileReader fr = new FileReader("D:\\Graduation\\TestStudy\\src\\org\\itheima_01\\class.txt");
properties.load(fr);
fr.close();
String className = properties.getProperty("ClassName");
String methodName = properties.getProperty("MethodName");
Class<?> c = Class.forName(className);
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
Method method = c.getMethod(methodName);
method.invoke(obj);
}
}