Java_note_3

Java_note_3

Charles Lv7

Java_note Other

1.Error

folding code

Exception_demo1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package note_file.other.Error;

public class Exception_demo1 {
public static void main(String[] args) {
System.out.println("begin");
method();
System.out.println("end");
}

public static void method() {
try {
int[] arr = { 1, 2, 3 };
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {// catch(异常类名 变量名)[这段代码里的变量名似乎什么都可以]
System.out.println("index_no_exist");
e.printStackTrace();// 输出异常位置,内容和原因
System.out.println(e.getMessage());// 输出异常原因
System.out.println(e.toString());// 异常原因加getMessage的内容
}

/*
* Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3
* out of bounds for length 3
* at note_file.other.Error.Exception_demo1.method(Exception_demo1.java:12)
* at note_file.other.Error.Exception_demo1.main(Exception_demo1.java:6)
*/
}
}

Exception_demo2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package note_file.other.Error;

public class Exception_demo1 {
public static void main(String[] args) {
System.out.println("begin");
method();
System.out.println("end");
}

public static void method() {
try {
int[] arr = { 1, 2, 3 };
System.out.println(arr[3]);
} catch (ArrayIndexOutOfBoundsException e) {// catch(异常类名 变量名)[这段代码里的变量名似乎什么都可以]
System.out.println("index_no_exist");
e.printStackTrace();// 输出异常位置,内容和原因
System.out.println(e.getMessage());// 输出异常原因
System.out.println(e.toString());// 异常原因加getMessage的内容
}

/*
* Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3
* out of bounds for length 3
* at note_file.other.Error.Exception_demo1.method(Exception_demo1.java:12)
* at note_file.other.Error.Exception_demo1.main(Exception_demo1.java:6)
*/
}
}

Score_Exception.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package note_file.other.Error;

public class Score_Exception extends Exception {// 自己编写继承Exception或RuntimeException的类为自定义异常

public Score_Exception() {
}

public Score_Exception(String message) {
super(message);
}

}

Teacher_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package note_file.other.Error;

import java.util.Scanner;

public class Teacher_demo {
public static void main(String[] args) {
try (Scanner sc = new Scanner(System.in)) {
int score = sc.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(score);
} catch (Score_Exception e) {
e.printStackTrace();
}
}
}
}

Teacher.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package note_file.other.Error;

public class Teacher {
public void checkScore(int score) throws Score_Exception {
if (score < 0 || score > 100) {
// throw new Score_Exception();
throw new Score_Exception("分数应在0到100之间");
// throws用在方法声明后面,跟的是异常类名,表示抛出异常,由该方法的调用者处理,只表示出现异常的一种可能性,并不一定出现这些异常
// throw用在方法体内,跟的是异常对象名,表示抛出异常,由该方法体内的语句处理,一定出现这些异常
} else {
System.out.println("分数异常");
}
}
}

2.Generic

folding code

Generic_Class.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package note_file.other.Generic;
// 泛型类

public class Generic_Class<T> {
private T t;

public Generic_Class() {
}

public Generic_Class(T t) {
this.t = t;
}

public T getT() {
return t;
}

public void setT(T t) {
this.t = t;
}

}

Generic_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package note_file.other.Generic;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Generic_demo {
// 泛型
public static void main(String[] args) {
Collection<String> c = new ArrayList<>();
c.add("hello");
c.add("world");
// c.add(100);因为利用了泛型(即<>中的内容以限制变量类型),所以这里会报错,若不用<>则会正常输出,但会有警告
Iterator<String> it = c.iterator();
while (it.hasNext()) {
Object obj = it.next();
System.out.println(obj);
}

// 泛型类
Generic_Class<String> g1 = new Generic_Class<>();
g1.setT("杜金阳");
System.out.println(g1.getT());
Generic_Class<Integer> g2 = new Generic_Class<>();
g2.setT(100);
System.out.println(g2.getT());
// 泛型方法
Generic_method g = new Generic_method();
g.show("杜金阳");
g.show(100);
// 泛型接口
Generic_interface<String> g3 = new Generic_Impl<>();
g3.show("Lily");
Generic_interface<Integer> g4 = new Generic_Impl<>();
g4.show(19);
// 类型通配符
// 注:在以下demo中Integer父类是Number,Number父类为Object
List<?> list1 = new ArrayList<Object>();
List<?> list2 = new ArrayList<Number>();
List<?> list3 = new ArrayList<Integer>();

// List<? extends Number> list4 = new ArrayList<Object>();[报错]
// extends表示该类型及子类型[类型通配符上限]
List<? extends Number> list5 = new ArrayList<Number>();
List<? extends Number> list6 = new ArrayList<Integer>();

List<? super Number> list7 = new ArrayList<Object>();
List<? super Number> list8 = new ArrayList<Number>();
// List<? super Number> list9 = new ArrayList<Integer>();[报错]
// super表示该类型及父类型[类型通配符下限]

}
}

Generic_lmpl.java

1
2
3
4
5
6
7
8
9
10
package note_file.other.Generic;

public class Generic_Impl<T> implements Generic_interface<T> {
@Override
public void show(T t) {
System.out.println(t);
}

}

Generic_interface.java

1
2
3
4
5
6
package note_file.other.Generic;

public interface Generic_interface<T> {
void show(T t);
}

Generic_method.java

1
2
3
4
5
6
7
8
package note_file.other.Generic;

public class Generic_method {
public <T> void show(T t) {
System.out.println(t);
}
}

3.Interface_demo

Function_Interface

folding code

Consumer_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package note_file.other.Interface_demo.Function_Interface;

import java.net.SocketTimeoutException;
import java.util.function.Consumer;

public class Consumer_demo {
public static void main(String[] args) {
operatorString("charles", (String s) -> {
System.out.println(s);
}, (String s) -> {
System.out.println((new StringBuilder(s).reverse().toString()));
});

}

public static void operatorString(String name, Consumer<String> con1, Consumer<String> con2) {// Consumer为消费型接口
con1.andThen(con2).accept(name);
}
}

Function_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package note_file.other.Interface_demo.Function_Interface;

import java.util.function.Function;

public class Function_demo {
public static void main(String[] args) {
convert("100", s -> Integer.parseInt(s));
convert("100", Integer::parseInt);
}

public static void convert(String s, Function<String, Integer> fun) {// Function接口
int i = fun.apply(s);
System.out.println(i);
}
}

MyInterface_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package note_file.other.Interface_demo.Function_Interface;

public class MyInterface_demo {
public static void main(String[] args) {
MyInterface my = () -> System.out.println("函数式接口");
my.show();
// 函数式接口作为方法的参数
startThread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ": 线程启动了");
};
});

startThread(() -> System.out.println(Thread.currentThread().getName() + ": 线程启动了"));
// 如果方法是个函数式接口,可以使用Lambda表达式作为参数传递

}

private static void startThread(Runnable r) {
Thread t = new Thread(r);
t.start();
}
}

MyInterface.java

1
2
3
4
5
6
7
package note_file.other.Interface_demo.Function_Interface;

@FunctionalInterface // 函数式接口的注解,建议加上
public interface MyInterface {
void show();
}

Predicate_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package note_file.other.Interface_demo.Function_Interface;

import java.util.function.Predicate;

public class Predicate_demo {
public static void main(String[] args) {
boolean b1 = checkString1("hello", s -> s.length() > 8);
System.out.println(b1);
boolean b2 = checkString2("hello world", s -> s.length() > 8);
System.out.println(b2);
boolean b3 = checkString3("hello world", s -> s.length() > 8, s -> s.length() < 15);
System.out.println(b3);
boolean b4 = checkString4("hello world", s -> s.length() > 8, s -> s.length() < 15);
System.out.println(b4);
}

public static boolean checkString1(String s, Predicate<String> pre) {
// Predicate接口通常用于参数是否满足指定的条件
return pre.test(s);
}

public static boolean checkString2(String s, Predicate<String> pre) {
return pre.negate().test(s);
/*
* 相当于return !pre.test(s);
*/
}

public static boolean checkString3(String s, Predicate<String> pre1, Predicate<String> pre2) {
return pre1.and(pre2).test(s);// 逻辑和操作
}

public static boolean checkString4(String s, Predicate<String> pre1, Predicate<String> pre2) {
return pre1.or(pre2).test(s);// 逻辑或操作
}
}

Supplier_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package note_file.other.Interface_demo.Function_Interface;

import java.util.function.Supplier;

public class Supplier_demo {
public static void main(String[] args) {
String s = getString(() -> {
return "I love my Mum";
});
System.out.println(s);

}

private static String getString(Supplier<String> sup) {// Supplier是生产型接口
return sup.get();
}
}

Updated

folding code

MyInterface_demo.java

1
2
3
4
5
6
7
8
9
10
11
package note_file.other.Interface_demo.Updated;

public class MyInterface_demo {
public static void main(String[] args) {
MyInterface my = new MyInterfaceImpl1();
my.show1();
my.show2();
my.show3();// 调用默认方法
MyInterface.show4();// 调用静态方法
}
}

MyInterface.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package note_file.other.Interface_demo.Updated;

public interface MyInterface {
void show1();

void show2();

public default void show3() {// 默认方法[public可以省略不写]
method1();// 调用私有方法
method2();// 调用私有静态方法
System.out.println("show3");
}// 默认方法也可以在接口实现类中重写,只是不一定要重写,但如果有同名的默认方法,必须重写

public static void show4() {// 静态方法[public可以省略不写]
method2();// 调用静态私有方法,私有方法调用会报错
System.out.println("show4");
}// 静态方法只能被接口调用,接口实现类不能调用

// 私有方法:可以用于提取相同的代码实现
private void method1() {
System.out.println("2022 NBA champion");
System.out.println("hello Stephen Curry");
}

private static void method2() {
System.out.println("2022 NBA champion");
System.out.println("hello Stephen Curry");
}

}

MyInterfacelmpl1.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package note_file.other.Interface_demo.Updated;

public class MyInterfaceImpl1 implements MyInterface {
@Override
public void show1() {
System.out.println("1:show1");
}

@Override
public void show2() {
System.out.println("1:show2");
}
}

MyInterfacelmpl2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package note_file.other.Interface_demo.Updated;

public class MyInterfaceImpl2 implements MyInterface {
@Override
public void show1() {
System.out.println("2:show1");
}

@Override
public void show2() {
System.out.println("2:show2");
}
}

other

folding code

Cat.java

1
2
3
4
5
6
7
8
9
10
11
package note_file.other.Interface_demo.other;

public class Cat implements Jumping {
// 类和接口之间使用关键字implements
@Override
public void jump() {
System.out.println("猫可以跳高了");
}

}

Inter.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package note_file.other.Interface_demo.other;

public interface Inter {
public int num1 = 10;
public final int num2 = 20;
public static final int num3 = 30;
int num4 = 40;

// 以上四行的实际设置均为num3的形式,即用static和final修饰
// public Inter(){}[报错]
// 接口中不能设置构造方法
// public void show() {}[报错]
// 接口中不能设置具体方法,但可以设置抽象方法体

public abstract void method();

void show();
// 以上两行等效,即接口中均为抽象方法体
}

Interface_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package note_file.other.Interface_demo.other;

public class Interface_demo {
public static void main(String[] args) {
// Inter i = new InterImpl();
// i.num1 = 20;[报错]
// System.out.println(i.num1);// [这种写法有警告但可以输出]
// i.num2 = 40;[报错]
System.out.println(Inter.num2);
System.out.println(Inter.num3);
/*
* Summary:
* 1.类与类的关系:单继承,多层继承
* 2.类与接口关系:多实现,并且可以在继承类后多实现接口(即可以实现public class InterImpl extends Object
* implements Inter1,Inter2,Inter3的写法)
* 3.接口与接口关系:多继承(即可以实现public interface Inter3 extends Inter1,Inter2 的写法)
* 4.抽象类是对事物的抽象,接口是对行为的抽象
*/
}
}

Interlmpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package note_file.other.Interface_demo.other;

public class InterImpl implements Inter {
// public class InterImpl extends Object implements Inter{
// 上面两种写法等效(Object类是所以类的共同根类)[一个类如果没有父类,默认继承自Object类]
@Override
public void method() {
System.out.println("method");

}

@Override
public void show() {
System.out.println("show");

}

}

Jumping_demo.java

1
2
3
4
5
6
7
8
9
10
package note_file.other.Interface_demo.other;

public class Jumping_demo {
public static void main(String[] args) {
Jumping j = new Cat();
// 接口本身类似抽象类,需要通过多态来实体化
j.jump();
}
}

Jumping.java

1
2
3
4
5
6
7
8
9
10
11
12
package note_file.other.Interface_demo.other;

public interface Jumping {
/*
* 接口:
* 1.接口本身是抽象内容,不能直接实体化
* 2.接口用关键字interface修饰
* 3.类实现接口用implements表示
*/
public abstract void jump();
}

4.IO

File

folding code

file_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package note_file.other.IO.File_Class;

import java.io.File;
import java.io.IOException;

public class file_demo {
public static void main(String[] args) throws IOException {
// File类创建方法
// 方法1
File f1 = new File(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\File_Class\\file1.txt");
System.out.println(f1);
// 方法2
File f2 = new File("D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\File_Class",
"file1.txt");
System.out.println(f2);
// 方法3
File f3 = new File("D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\File_Class");
File f4 = new File(f3, "file1.txt");
System.out.println(f4);

// File类创建功能
File f = new File("D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\File_Class");
File file1 = new File(f, "file1.txt");
file1.createNewFile();// 创建文件
File file2 = new File(f, "JavaSE");
file2.mkdir();// 创建目录
File file3 = new File(f, "JavaWEB\\HTML");
file3.mkdirs();// 创建多级目录
// 注:若出现同名文件或文件和目录名字相同,则无法成功创建

// File类判断和获取功能
System.out.println(file1.isDirectory());// 是否为目录
System.out.println(file1.isFile());// 是否为文件
System.out.println(file1.exists());// 是否存在
System.out.println(file1.getAbsolutePath());// 返回该抽象路径的绝对路径字符串
System.out.println(file1.getPath());// 将此抽象路径名转化为路径名字符串
System.out.println(file1.getName());// 返回文件或路径的名字
String[] list = f.list();// 返回该目录中文件及目录形成的字符串数组
for (String s : list) {
System.out.println(s);
}
File[] listFiles = f.listFiles();// 返回该目录中文件及目录形成的File数组
for (File file : listFiles) {
System.out.println(file);
System.out.println(file.getName());
if (file.isFile()) {
System.out.println(file);
}
}
// File类删除功能
file1.delete();
file2.delete();
file3.delete();
File file4 = new File(f, "JavaWEB");
// 当目录下有文件时,目录不能直接删除
file4.delete();
}
}

IOStream

folding code

BufferStream_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package note_file.other.IO.IOStream_Class;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class BufferStream_demo {
public static void main(String[] args) throws IOException {
// 字节缓冲输出流
// FileOutputStream fos= new
// FileOutputStream("D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
// BufferedOutputStream bos=new BufferedOutputStream(fos);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt"));
bos.write("hello\r\n".getBytes());
bos.write("world\r\n".getBytes());
bos.close();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt"));
int by;
while ((by = bis.read()) != -1) {
System.out.print((char) by);
}
byte[] bys = new byte[1024];// 正常为1024及其整数倍
int len;
while ((len = bis.read(bys)) != -1) {
System.out.println(new String(bys, 0, len));
}
bis.close();
}
}

ConversionStream_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package note_file.other.IO.IOStream_Class;
//字符流

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class ConversionStream_demo {
public static void main(String[] args) throws IOException {
OutputStream fos = new FileOutputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write("中国");
osw.flush();// 记得写完要刷新

InputStream fis = new FileInputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
int ch;
while ((ch = isr.read()) != -1) {
System.out.print((char) ch);
}
// 字符流写数据的五种方法
osw.write(97);// 此时字符流位于缓冲区,未写入文件,需要之后flush刷新流才能写入文件
osw.flush();
char[] chs = { 'a', 'b', 'c', 'd', 'e', '\r', '\n' };
osw.write(chs);
osw.write(chs, 0, 2);
osw.write("abcde\r\n");
osw.write("abcde\r\n", 0, "abcd".length());
// 字符流读入数据的两种方式
isr.read();
isr.read(chs);
// 字符缓冲流
FileWriter fw = new FileWriter(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write("hello\r\n");
bw.write("world\r\n");
bw.flush();

FileReader fr = new FileReader(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println(br.readLine());// 读一行数据
int chr;
while ((chr = br.read()) != -1) {
System.out.print((char) chr);
}
bw.newLine();// 写一行分隔符,适应不同系统自动设置

char[] chrs = new char[1024];
int len;
while ((len = br.read(chrs)) != -1) {
System.out.println(new String(chrs, 0, len));
}

osw.close();// 关闭流之前会先flush一次
isr.close();
fos.close();
bw.close();
br.close();
fw.close();
fr.close();
}
}

FileInputStream.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package note_file.other.IO.IOStream_Class;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStream_Class {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
int by;// 从输入流读取一个字节的数据
while ((by = fis.read()) != -1) {
// System.out.print(by);// ASCII码
System.out.print((char) by);
}
// 按字节数组输出
byte[] bys = new byte[1024];// 正常为1024及其整数倍
int len;
while ((len = fis.read(bys)) != -1) {
System.out.println(new String(bys, 0, len));
}
fis.close();
}
}

FileOutputStream.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package note_file.other.IO.IOStream_Class;

import java.io.FileOutputStream;
import java.io.IOException;

//如果用记事本打开可以看懂则为字符流,否则则为字节流
public class FileOutputStream_Class {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
fos.write(97);// ASCII码
fos.write("\n".getBytes());

// File file = new File(
// "D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
// FileOutputStream fos2 = new FileOutputStream(file);
// 这种写法和上面的一样
// 写数据的三种方式
// 方式1:
fos.write(97);
fos.write(98);
fos.write(99);
fos.write(100);
fos.write(101);
fos.write("\n".getBytes());

// 方式2:
byte[] bys1 = { 97, 98, 99, 100, 101 };
fos.write(bys1);
fos.write("\n".getBytes());
/*
* 字节流换行细节:
* 1.Windows:\r\n
* 2.linus:\n
* 3.mac:\r
*/
byte[] bys2 = "abcde".getBytes();
fos.write(bys2);
fos.write("\n".getBytes());
// 方式3:
fos.write(bys2, 1, bys2.length - 1);// bys2的off位置写len的长度
fos.write("\n".getBytes());
// 文件追加写入
FileOutputStream fos2 = new FileOutputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt", true);// append为true代表可以追加写入
try {
fos2.write("djy gets 100 point\n".getBytes("UTF-8"));// 这里面可以编写编码方式,不写也可以
} catch (IOException e) {
e.printStackTrace();
} finally {// finally语句除非JVM强制退出,否则一定会执行
fos2.close();
}

fos.close();
fos2.close();
}
}

ObjectOutputStream_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package note_file.other.IO.IOStream_Class;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectOutputStream_demo {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt"));// 对象序列化流
Student s = new Student("charles", 19);
// 序列化对象
oos.writeObject(s);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt"));// 对象反序列化流
Object obj = ois.readObject();
Student s2 = (Student) obj;
System.out.println(s2.getName() + "," + s2.getAge());

oos.close();
ois.close();
}
}

Properties_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package note_file.other.IO.IOStream_Class;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

// Properties作为Map集合使用,底层为Hashtable方法
public class Properties_demo {
public static void main(String[] args) throws IOException {
// Properties<String,String> prop=new Properties<>();//错误写法
Properties prop = new Properties();
prop.put("21373191", "charles");
prop.put("21373119", "mumu");
// Properties特有方法
prop.setProperty("21373188", "tom");
System.out.println(prop.getProperty("21373191"));
Set<String> names = prop.stringPropertyNames();
for (String key : names) {
System.out.println(key);
} // 输出键的集合
// 遍历
// 方式1
Set<Object> keySet = prop.keySet();
for (Object key : keySet) {
Object value = prop.get(key);
System.out.println(key + "," + value);
}
// 方式2
for (String key : names) {
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}

// Properties和IO流结合
FileWriter fw = new FileWriter(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
prop.store(fw, null);// 第二个参数为描述信息,没有就写null
fw.close();

FileReader fr = new FileReader(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
prop.load(fr);
fr.close();
System.out.println(prop);
}
}

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package note_file.other.IO.IOStream_Class;

import java.io.Serializable;

public class Student implements Serializable {// ObjectOutputStream需要的接口
// 该接口为标记接口,不需要重写任何方法
private String name;
private transient int age;// transient修饰可以避免被序列化

public Student() {
}

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

}

System_in_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package note_file.other.IO.IOStream_Class;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;

public class System_in_demo {
public static void main(String[] args) throws IOException {
InputStream is = System.in;// 从键盘读入数据
int by;
while ((by = is.read()) != -1) {
System.out.print((char) by);
}
// 通过转换流将字节流转换为字符流[这种方式可以实现读汉字]
InputStreamReader isr = new InputStreamReader(is);
// 使用字符流读一行
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();// 读入字符串
System.out.println(s);
int i = Integer.parseInt(br.readLine());// 读入整数
System.out.println(i);
// 以上代码可以直接用Scanner类进行简化

PrintStream ps = System.out;
// System.out的本质是一个字节输出流
ps.println("hello");
ps.print(100);

// 打印流
PrintStream ps2 = new PrintStream(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt");
ps2.write(97);
ps2.flush();
ps2.print(97);// 这行与上面两行作用相同
// 注:使用继承父类的方法写数据,查看时会转码,使用自己的特有方法(如print)时,查看数据原样输出
ps2.println();// 换行
ps2.close();
// 字符打印流
PrintWriter pw = new PrintWriter(new FileWriter(
"D:\\coding_file\\study\\JAVA_file\\file_for_VScode\\note_file\\other\\IO\\IOStream_Class\\fos.txt"), true);// 第二个参数设为true可以实现自动刷新
pw.write("hello");
pw.flush();
pw.println(" hello");

OutputStreamWriter osw = new OutputStreamWriter(ps);
BufferedWriter bw = new BufferedWriter(osw);
bw.newLine();
bw.close();
ps.close();
pw.close();
}
}

5.Lambda

Method_Cite

folding code

Converter_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package note_file.other.Lambda.Method_Cite;

public class Converter_demo {
public static void main(String[] args) {
// useConverter((String s) -> {
// return Integer.parseInt(s);
// });
useConverter(s -> Integer.parseInt(s));
// 引用类方法
useConverter(Integer::parseInt);

}

private static void useConverter(Converter c) {
int num = c.convert("666");
System.out.println(num);
}
}

Converter.java

1
2
3
4
5
6
package note_file.other.Lambda.Method_Cite;

public interface Converter {
int convert(String s);
}

Printable_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package note_file.other.Lambda.Method_Cite;

public class Printable_demo {
public static void main(String[] args) {
// Lambda表达式
usePrintable(s -> System.out.println(s));
// 方法引用符::
usePrintable(System.out::println);
// 可推导的就是可省略的
}

private static void usePrintable(Printable p) {
p.printString("爱生活爱Java");
}
}

Printable.java

1
2
3
4
5
6
package note_file.other.Lambda.Method_Cite;

public interface Printable {
void printString(String s);
}



Lambda_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package note_file.other.Lambda;

public class Lambda_demo1 {
public static void main(String[] args) {
// 方法1:实现类的方式
My_Runnable my = new My_Runnable();
Thread t = new Thread(my);
t.start();
// 方法2:匿名内部类方式改进
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("多线程程序启动了");
};
}).start();
// 方法3:Lambda表达式改进
new Thread(() -> {
System.out.println("多线程程序启动了");
}).start();
/*
* Lambda表达式:
* 1.Lambda表达式中()表示参数为空,->指向后面要做的事
* 2.Lambda表达式的省略模式是指()函数中的参数类型可以省略不写,但不能只省略一个
* 3.Lambda表达式中如果参数有且仅有一个,()也可以省略
* 4.如果代码块的语句只有一条,可以省略{}和 ;,在这种情况下,如果有return也要省略
* [即可以有use(s->System.out.println(s));的写法]
* 5.Lambda表达式只能适用于接口,不能用于抽象类和具体类
*/

}
}

My_Runnable.java

1
2
3
4
5
6
7
8
9
package note_file.other.Lambda;

public class My_Runnable implements Runnable {
@Override
public void run() {
System.out.println("多线程程序启动了");
}
}

6.Modifier

Static_demo

folding code

Static_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package note_file.other.Modifier.Static_demo;

public class Static_demo {
public static void main(String[] args) {
Student.university = "Bei hang university";
// 通过类来访问static修饰的变量的方法
Student s1 = new Student("charles", 19);
Student s2 = new Student("Tangming", 17);
s1.show();
s2.show();
}
}

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package note_file.other.Modifier.Static_demo;

public class Student {
public String name;
public int age;

public static String university;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public void show() {
System.out.println(name + " ," + age + " ," + university);
}

public void show1() {
/*
* 非静态的成员方法:
* 1.能访问非静态的成员变量
* 2.能访问静态的成员变量
* 3.能访问非静态的成员方法
* 4.能访问静态的成员方法
*/
}

public void show2() {
System.out.println(name);
System.out.println(university);
show1();
show3();
}

public static void show3() {
/*
* 静态的成员变量:
* 1.能访问静态的成员变量
* 2.能访问静态的成员方法
*/
}

public static void show4() {
// System.out.println(name);[报错]
System.out.println(university);
// show1();[报错]
show3();
}
}



Modifier.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package note_file.other.Modifier;

public class Modifier {
public void my_Package() {
// 格式:package 包名;(多级包用点分开)
// 自动建包 javac -d ***.java
// 通过import进行导包
// 格式:import 包名;
}

public void my_Modifier() {
/*
* 权限修饰符:
* 1.private :只能在本类内被访问
* 2.默认 :只能在同一个包内被访问
* 3.protected :可以在不同的包的子类里访问
* 4.public:在不同的包的无关类里也可以访问
*/
/*
* final:
* 1.被final修饰的方法不可被重写(eg. public final void method();)[最终方法]
* 2.被final修饰的基本类型变量不可被重新赋值,所指地址可以改变(eg. public final int age = 20;)[常量]
* 3.被final修饰的引用类型变量所指的地址不可以被改变,内容可以重新赋值(eg. final Student s=new
* Student();)[常指针]
* 4.被final修饰的类不可被子类继承(eg. public final class Fu();)[最终类]
*/
/*
* static:
* 1.被类的所有对象共享
* 2.可以通过类和对象两种方式访问(建议使用类来访问)
* 3.访问特点:
* * 非静态的成员方法:
* (1).能访问非静态的成员变量
* (2).能访问静态的成员变量
* (3).能访问非静态的成员方法
* (4).能访问静态的成员方法
* * 静态的成员变量:
* (1).能访问静态的成员变量
* (2).能访问静态的成员方法
*/

}

}

7.Net

folding code

Client_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package note_file.other.Net;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client_demo {
public static void main(String[] args) throws UnknownHostException, IOException {
// Socket s = new Socket(InetAddress.getByName("192.168.2.106"), 10086);
// 上面这种方式也可以
Socket s = new Socket("192.168.2.106", 10086);
// 获取输出流,写数据
OutputStream os = s.getOutputStream();
os.write("hello,TCP".getBytes());
s.close();

}
}

InetAddress_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package note_file.other.Net;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class InetAddress_demo {
public static void main(String[] args) throws UnknownHostException {
InetAddress address = InetAddress.getByName("192.168.2.106");// 确定主机名的ip地址,主机名称可以是IP地址或机器名称
String name = address.getHostName();// 获得ip地址
String ip = address.getHostAddress();// 返回文本形式IP地址字符串
System.out.println("主机名: " + name + "\r\n" + "ip地址: " + ip);
}
}

Server.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package note_file.other.Net;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static void main(String[] args) throws IOException {
// 创建绑定到指定端口的服务器套接字
ServerSocket ss = new ServerSocket(10086);
// 侦听要接受此套接字并接受它
Socket s = ss.accept();
// 获取输入流,读数据
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String data = new String(bys, 0, len);
System.out.println("数据是:" + data);
s.close();
ss.close();
}
}

UCP_Receive_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package note_file.other.Net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UCP_Receive_demo {
public static void main(String[] args) throws IOException {
// 创建接收端的Socket对象
DatagramSocket ds = new DatagramSocket(10086);
// 创建一个数据包,用于接受数据
byte[] bys = new byte[1024];
DatagramPacket dp = new DatagramPacket(bys, bys.length);
ds.receive(dp);
// 解析数据包
byte[] data_s = dp.getData();
int len = dp.getLength();
String data = new String(data_s, 0, len);
System.out.println(data);

ds.close();
}
}

UCP_Send_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package note_file.other.Net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UCP_Send_demo {
public static void main(String[] args) throws IOException {
// 创建发送端的Socket对象
DatagramSocket ds = new DatagramSocket();
// 创建数据,并将数据打包
byte[] bys = "hello udp".getBytes();
int length = bys.length;
InetAddress address = InetAddress.getByName("192.168.2.106");
int port = 10086;// 端口号为[0,65536]均可,[0,1023]最好不要使用
DatagramPacket dp = new DatagramPacket(bys, length, address, port);
ds.send(dp);
ds.close();
}
}

8.Reflection

folding code

ClassLoader_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package note_file.other.Reflection;

//类加载器
public class ClassLoader_demo {
public static void main(String[] args) {
ClassLoader c1 = ClassLoader.getSystemClassLoader();
System.out.println(c1);// AppClassLoader
ClassLoader c2 = c1.getParent();
System.out.println(c2);// PlatformClassLoader
ClassLoader c3 = c2.getParent();
System.out.println(c3);// null

}
}

Reflect_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package note_file.other.Reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflect_demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException,
InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchFieldException {
// 三种方式获得Class对象:
// 1.使用类的class属性来获取该类对应的Class对象
Class<Student> c1 = Student.class;
Class<Student> c2 = Student.class;
System.out.println(c2);
System.out.println(c1 == c2);
System.out.println("");

// 2.调用对象getClass()方法
Student s = new Student();
Class<? extends Student> c3 = s.getClass();
System.out.println(c3);
System.out.println(c1 == c3);
System.out.println("");

// 3.调用Class类中静态方法forName()
Class<?> c4 = Class.forName("note_file.other.Reflection.Student");
System.out.println(c4);
System.out.println(c1 == c4);
System.out.println("");

// 反射获取构造方法并使用
Class<?> c = Class.forName("note_file.other.Reflection.Student");
Constructor<?>[] cons = c.getConstructors();// 获得公共的构造方法
for (Constructor<?> con : cons) {
System.out.println(con);
}
System.out.println("");

Constructor<?>[] d_cons = c.getDeclaredConstructors();// 获得所有构造方法
for (Constructor<?> con : d_cons) {
System.out.println(con);
}
System.out.println("");

Constructor<?> con = c.getConstructor();// 获得单个公共构造方法对象
Object obj = con.newInstance();
System.out.println(obj);
System.out.println("");

Constructor<?> d_con = c.getDeclaredConstructor();// 获得单个构造方法对象
Object d_obj = d_con.newInstance();
System.out.println(d_obj);
System.out.println("");

// 反射获取成员变量并使用
Field[] fields = c.getFields();// 获得公共的成员变量
for (Field field : fields) {
System.out.println(field);
}
System.out.println("");

Field[] d_fields = c.getDeclaredFields();// 获得所有的成员变量
for (Field d_field : d_fields) {
System.out.println(d_field);
}
System.out.println("");

Field field = c.getField("address");// 获得单个的公共成员变量
System.out.println(field);
Constructor<?> con_f = c.getConstructor();
Object obj_f = con_f.newInstance();
field.set(obj_f, "合肥");// 给obj_f的成员变量field赋值为合肥
System.out.println(obj_f);
System.out.println("");

Field d_field = c.getDeclaredField("age");// 获得单个的成员变量
System.out.println(d_field);
System.out.println("");

// 反射获取成员方法并使用
Method[] methods = c.getMethods();// 获得所有公共方法
// 方法对象反映由该Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象及超类和超级接口继承的类
for (Method method : methods) {
System.out.println(method);
}
System.out.println("");

Method[] d_methods = c.getDeclaredMethods();// 获得所有方法
// 该方法获取的成员方法不包括继承的方法
for (Method d_method : d_methods) {
System.out.println(d_method);
}

Method method = c.getMethod("method1");// 获得单个公共方法
Object obj_m = c.getConstructor().newInstance();
method.invoke(obj_m);

Method d_method = c.getDeclaredMethod("method1");// 获得单个方法
Object d_obj_m = c.getConstructor().newInstance();
d_method.invoke(d_obj_m);
}
}

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package note_file.other.Reflection;

public class Student {
// 成员变量:一个私有,一个默认,一个公共
private String name;
int age;
public String address;
// 构造方法:一个私有,一个默认,两个公共

public Student() {
}

private Student(String name) {
this.name = name;
}

Student(String name, int age) {
this.name = name;
this.age = age;
}

public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}

// 成员方法:一个私有,四个公共
private void function() {
System.out.println("function");
}

public void method1() {
System.out.println("method");
}

public void method2(String s) {
System.out.println("method" + s);
}

public String method3(String s, int i) {
return s + "," + i;
}

@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ",age=" + age + ",address=" + address + '\'' + '}';
}
}

9.other

folding code

Args_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package note_file.other.other;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

//可变参数[本质是传入变量形成的数组]
public class Args_demo {
public static void main(String[] args) {
System.out.println(sum(10, 120, 30));
System.out.println(sum(1, 2, 3, 4, 5, 6, 7));

// 可变参数的使用
List<String> list = Arrays.asList("hello", "world", "java");// asList是一个可变参数
// list.add("NBA");[报错]
// list.remove("NBA");[报错]
list.set(0, "NBA");
System.out.println(list);
// 只可以进行修改,不能添加或删除

List<String> list_of = List.of("hello", "world", "java", "world");
// list_of.add("NBA");[报错]
// list_of.remove("NBA");[报错]
// list_of.set(0, "NBA");[报错]
System.out.println(list_of);
// 增删改均不可以

Set<String> set = Set.of("hello", "world", "java", "world");
// set.add("NBA");[报错]
// set.remove("NBA");[报错]
System.out.println(set);
// 增删均不可,Set没有改方法

}

public static int sum(int b, int... a) {// 如果有多个参数,需要将可变参数放在方法体的后面
int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum * b;
}
}

Stream_demo.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package note_file.other.other;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Stream_demo {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<>();
array.add("charles");
array.add("张三丰");
array.add("张飞");
array.add("张无忌");
// 利用Stream流输出姓张且名字长度为3的集合元素
array.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() == 3).forEach(System.out::println);

// Stream流的常见生成方式
// 1.Collection体系的集合可以使用默认方法生成stream()生成流
List<String> list = new ArrayList<>();
list.add("50");
list.add("10");
list.add("30");
list.add("40");
list.add("20");

Stream<String> list_stream = list.stream();

Set<Integer> set = new HashSet<>();
set.add(10);
set.add(50);
set.add(20);
set.add(30);
set.add(40);
Stream<Integer> set_stream = set.stream();
// 2.Map体系的;
// 2.Map体系的;集合间接生成流
// 2.Map体系的;集合间接生成流
// 2.Map体系的;集合间接生成流
// 2.Map体系的;集合间接生成流集合间接生成流
Map<String, Integer> map = new HashMap<>();
map.put("charles", 21373191);
map.put("Tom", 21373188);
map.put("Jerry", 21373181);
Stream<String> key_stream = map.keySet().stream();
Stream<Integer> value_stream = map.values().stream();
Stream<Entry<String, Integer>> entryset_stream = map.entrySet().stream();

// 3.数组可以通过Stream接口的静态方法of(T...values)生成流
String[] strArray = { "hello", "world", "NBA" };
Stream<String> strArray_stream = Stream.of(strArray);

// Stream流的常见中间操作方法
// 1.利用filter过滤
array.stream().filter(s -> s.startsWith("张")).filter(s -> s.length() == 3).forEach(System.out::println);
// 2.利用limit限制符合要求元素的数目
array.stream().limit(3).forEach(System.out::println);
// 3.利用skip跳过一定数量符合要求的元素
array.stream().skip(2).limit(2).forEach(System.out::println);

Stream<String> s1 = array.stream().limit(2);
Stream<String> s2 = array.stream().skip(1);
// 4.concat方法用于合并两个流, distinct()用于输出不重复的元素
Stream.concat(s1, s2).distinct().forEach(System.out::println);
// 5.sorted()默认是按照字母顺序输出
strArray_stream.sorted().forEach(System.out::println);
// 按照字符串长度输出
Stream.of(strArray).sorted((m1, m2) -> m1.length() - m2.length()).forEach(System.out::println);
// 6.字符串转化为int输出[可以使用mapToInt(),使用该方法返回值为IntStream,有许多好用的方法]
list.stream().map(Integer::parseInt).forEach(System.out::println);
int result = list.stream().mapToInt(Integer::parseInt).sum();// 调用IntStream中的sum方法
System.out.println(result);
// 注:以上几种操作可以混合使用

// Stream常见终结操作方法
// 1.forEach()对满足条件元素单独操作
array.stream().forEach(System.out::println);
// 2. count()返回满足条件元素的个数
long count = array.stream().filter(s -> s.startsWith("张")).count();
System.out.println(count);

// Stream流的收集操作
Stream<String> filter = list.stream().filter(s -> s.length() == 3);
List<String> names = filter.collect(Collectors.toList());
for (String name : names) {
System.out.println(name);
}
Stream<Integer> filter2 = set.stream().filter(age -> age > 25);
Set<Integer> ages = filter2.collect(Collectors.toSet());
for (int i : ages) {
System.out.println(i);
}

String[] nameArray = { "charles,19", "Lily,43", "long,50" };
Stream<String> filter3 = Stream.of(nameArray).filter(s -> Integer.parseInt(s.split(",")[1]) > 25);
Map<String, Integer> map2 = filter3
.collect(Collectors.toMap((s -> s.split(",")[0]), s -> Integer.parseInt(s.split(",")[1])));
Set<Entry<String, Integer>> entrySet = map2.entrySet();
for (Entry<String, Integer> me : entrySet) {
System.out.println(me.getKey() + "," + me.getValue());
}

}
}

  • Title: Java_note_3
  • Author: Charles
  • Created at : 2022-12-29 11:58:53
  • Updated at : 2023-02-09 09:45:39
  • Link: https://charles2530.github.io/2022/12/29/java-note-3/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments