package com.imooc;
/**
* 用户身份认证标记接口
*/
@FunctionalInterface
public interface IUserCredential {
/**
* 通过用户账号,验证用户身份信息的接口
* @param username 要验证的用户账号
* @return 返回身份信息[系统管理员、用户管理员、普通用户]
*/
String verifyUser(String username);
// boolean test();
default String getCredential(String username) {
// 模拟方法
if ("admin".equals(username)) {
return "admin + 系统管理员用户";
} else if("manager".equals(username)){
return "manager + 用户管理员用户";
} else {
return "commons + 普通会员用户";
}
}
}
package com.imooc;
/**
* 消息传输格式化转换接口
*/
@FunctionalInterface
public interface IMessageFormat {
/**
* 消息转换方法
* @param message 要转换的消息
* @param format 转换的格式[xml/json..]
* @return 返回转换后的数据
*/
String format(String message, String format);
// boolean test();
String toString();
/**
* 消息合法性验证方法
* @param msg 要验证的消息
* @return 返回验证结果
*/
static boolean verifyMessage(String msg) {
if (msg != null) {
return true;
}
return false;
}
}
package com.imooc.impl;
import com.imooc.IUserCredential;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.imooc.impl UserCredentialImpl
* <p>TODO</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class UserCredentialImpl implements IUserCredential {
@Override
public String verifyUser(String username) {
if ("admin".equals(username)) {
return "系统管理员";
} else if("manager".equals(username)) {
return "用户管理员";
}
return "普通会员";
}
}
package com.imooc.impl.impl;
import com.imooc.IMessageFormat;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.imooc.impl.impl MessageFormatImpl
* <p>TODO</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class MessageFormatImpl implements IMessageFormat {
@Override
public String format(String message, String format) {
System.out.println("消息转换...");
return message;
}
}
package imooclambda;
import com.imooc.IMessageFormat;
import com.imooc.IUserCredential;
import com.imooc.impl.UserCredentialImpl;
import com.imooc.impl.impl.MessageFormatImpl;
import java.util.Random;
import java.util.UUID;
import java.util.function.*;
/**
* Hello world!
*
* 需求改动:
* 所有的用户验证,可以同时获取用户的验证信息[是否认证成功|成功~返回用户|null]
*
* Lambda表达式 基本语法
*/
public class App
{
String welcome = "慕课网欢迎您.";
public static void main( String[] args ) {
// 一、接口的静态方法和默认方法
// 1. 默认方法
IUserCredential ic = new UserCredentialImpl();
System.out.println(ic.verifyUser("admin"));
System.out.println(ic.getCredential("admin"));
// 2. 静态方法
String msg = "hello world";
if (IMessageFormat.verifyMessage(msg)) {
IMessageFormat format = new MessageFormatImpl();
format.format(msg, "json");
}
// 匿名内部类,实现接口的抽象方法
IUserCredential ic2 = new IUserCredential() {
@Override
public String verifyUser(String username) {
return "admin".equals(username)?"管理员":"会员";
}
};
// 二、lambda表达式 是 函数式接口的一种实现
System.out.println(ic2.verifyUser("manager"));
System.out.println(ic2.verifyUser("admin"));
// lambda表达式,针对函数式接口的简单实现
IUserCredential ic3 = (String username) -> {
return "admin".equals(username)?"lbd管理员": "lbd会员";
};
System.out.println(ic3.verifyUser("manager"));
System.out.println(ic3.verifyUser("admin"));
}
}
/*
java.util.function提供了大量的函数式接口
Predicate 接收参数T对象,返回一个boolean类型结果
Consumer 接收参数T对象,没有返回值
Function 接收参数T对象,返回R对象
Supplier 不接受任何参数,直接通过get()获取指定类型的对象
UnaryOperator 接口参数T对象,执行业务处理后,返回更新后的T对象
BinaryOperator 接口接收两个T对象,执行业务处理后,返回一个T对象
*/
// 三、JDK8 提供的常见函数式接口
Predicate<String> pre = (String username) -> {
return "admin".equals(username);
};
System.out.println(pre.test("manager"));
System.out.println(pre.test("admin"));
Consumer<String> con = (String message) -> {
System.out.println("要发送的消息:" + message);
System.out.println("消息发送完成");
};
con.accept("hello 慕课网的学员们..");
con.accept("imooc lambda expression.");
Function<String, Integer> fun = (String gender) -> {
return "male".equals(gender)?1:0;
};
System.out.println(fun.apply("male"));
System.out.println(fun.apply("female"));
Supplier<String> sup = () -> {
return UUID.randomUUID().toString();
};
System.out.println(sup.get());
System.out.println(sup.get());
System.out.println(sup.get());
UnaryOperator<String> uo = (String img)-> {
img += "[100x200]";
return img;
};
System.out.println(uo.apply("原图--"));
BinaryOperator<Integer> bo = (Integer i1, Integer i2) -> {
return i1 > i2? i1: i2;
};
System.out.println(bo.apply(12, 13));
package imooclambda;
import com.imooc.IMessageFormat;
import com.imooc.IUserCredential;
import com.imooc.impl.UserCredentialImpl;
import com.imooc.impl.impl.MessageFormatImpl;
import java.util.Random;
import java.util.UUID;
import java.util.function.*;
/**
* Hello world!
*
* 需求改动:
* 所有的用户验证,可以同时获取用户的验证信息[是否认证成功|成功~返回用户|null]
*
* Lambda表达式 基本语法
*/
public class App
{
String welcome = "慕课网欢迎您.";
public static void main( String[] args ) {
// 1. lambda表达式的基本语法
/*
1)声明:就是和lambda表达式绑定的接口类型
2)参数:包含在一对圆括号中,和绑定的接口中的抽象方法中的参数个数及顺序一致。
3)操作符:->
4)执行代码块:包含在一对大括号中,出现在操作符号的右侧
[接口声明] = (参数) -> {执行代码块};
*/
ILambda1 i1 = () -> {
System.out.println("hello imooc!");
System.out.println("welcome to imooc!");
};
i1.test();
ILambda1 i2 = () -> System.out.println("hello imooc");
i2.test();
ILambda2 i21 = (String n, int a) -> {
System.out.println(n + "say: my year's old is " + a);
};
i21.test("jerry", 18);
ILambda2 i22 = (n, a) -> {
System.out.println(n + " 说:我今年" + a + "岁了.");
};
i22.test("tom", 22);
ILambda3 i3 = (x, y) -> {
int z = x + y;
return z;
};
System.out.println(i3.test(11, 22));
ILambda3 i31 = (x, y) -> x + y;
System.out.println(i31.test(100, 200));
/*
1. lambda表达式,必须和接口进行绑定。
2. lambda表达式的参数,可以附带0个到n个参数,括号中的参数类型可以不用指定,jvm在运行时,会自动根据绑定的抽象方法中电参数进行推导。
3. lambda表达式的返回值,如果代码块只有一行,并且没有大括号,不用写return关键字,单行代码的执行结果,会自动返回。
如果添加了大括号,或者有多行代码,必须通过return关键字返回执行结果。
*/
}
// 没有参数,没有返回值的lambda表达式绑定的接口
interface ILambda1{
void test();
}
// 带有参数,没有返回值的lambda表达式
interface ILambda2{
void test(String name, int age);
}
// 带有参数,带有返回值的lambda表达式
interface ILambda3 {
int test(int x, int y);
}
}
package imooclambda;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: imooclambda App2
* <p>lambda表达式 变量捕获</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class App2 {
String s1 = "全局变量";
// 1. 匿名内部类型中对于变量的访问
public void testInnerClass() {
String s2 = "局部变量";
new Thread(new Runnable() {
String s3 = "内部变量";
@Override
public void run() {
// 访问全局变量
// System.out.println(this.s1);// this关键字~表示是当前内部类型的对象
System.out.println(s1);
System.out.println(s2);// 局部变量的访问,~不能对局部变量进行数据的修改[final]
// s2 = "hello";
System.out.println(s3);
System.out.println(this.s3);
}
}).start();
}
// 2. lambda表达式变量捕获
public void testLambda() {
String s2 = "局部变量lambda";
new Thread(() -> {
String s3 = "内部变量lambda";
// 访问全局变量
System.out.println(this.s1);// this关键字,表示的就是所属方法所在类型的对象
// 访问局部变量
System.out.println(s2);
// s2 = "hello";// 不能进行数据修改,默认推导变量的修饰符:final
System.out.println(s3);
s3 = "labmda 内部变量直接修改";
System.out.println(s3);
}).start();
}
public static void main(String[] args) {
App2 app = new App2();
// app.testInnerClass();
app.testLambda();
}
}
package imooclambda;
import java.util.ArrayList;
import java.util.List;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: imooclambda App3
* <p>lambda表达式类型检查</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class App3 {
public static void test(MyInterface<String, List> inter) {
List<String> list = inter.strategy("hello", new ArrayList());
System.out.println(list);
}
public static void main(String[] args) {
test(new MyInterface<String, List>() {
@Override
public List strategy(String s, List list) {
list.add(s);
return list;
}
});
test((x, y) -> {
y.add(x);
return y;
// x.add(y);
// return x;
});
/*
(x,y)->{..} --> test(param) --> param==MyInterface --> lambda表达式-> MyInterface类型
这个就是对于lambda表达式的类型检查,MyInterface接口就是lambda表达式的目标类型(target typing)
(x,y)->{..} --> MyInterface.strategy(T r, R r)--> MyInterface<String, List> inter
--> T==String R==List --> lambda--> (x, y) == strategy(T t , R r)--> x==T==String y==R==List
lambda表达式参数的类型检查
*/
}
}
@FunctionalInterface
interface MyInterface<T, R> {
R strategy (T t, R r);
}
package imooclambda;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: imooclambda App4
* <p>方法重载对于lmabda表达式的影响</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class App4 {
interface Param1 {
void outInfo(String info);
}
interface Param2 {
void outInfo(String info);
}
// 定义重载的方法
public void lambdaMethod(Param1 param) {
param.outInfo("hello param1 imooc!");
}
public void lambdaMethod(Param2 param) {
param.outInfo("hello param2 imooc");
}
public static void main(String[] args) {
App4 app = new App4();
app.lambdaMethod(new Param1() {
@Override
public void outInfo(String info) {
System.out.println(info);
}
});
app.lambdaMethod(new Param2() {
@Override
public void outInfo(String info) {
System.out.println("------");
System.out.println(info);
}
});
/*
lambda表达式存在类型检查-> 自动推导lambda表达式的目标类型
lambdaMethod() -> 方法 -> 重载方法
-> Param1 函数式接口
-> Param2 函数式接口
调用方法-> 传递Lambda表达式-> 自动推导->
-> Param1 | Param2
*/
// app.lambdaMethod( (String info) -> {
// System.out.println(info);
// });
}
}
package com.imooc.test;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.imooc.test Test
* <p>
* 1. 静态方法引用的使用
* 类型名称.方法名称() --> 类型名称::方法名称
* 2. 实例方法引用的使用
* 创建类型对应的一个对象 --> 对象应用::实例方法名称
* 3. 构造方法引用的使用
* 类型对象的构建过程 --> 类型名称::new
* </p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class Test {
public static void main(String[] args) {
// 存储Person对象的列表
List<Person> personList = new ArrayList<>();
personList.add(new Person("tom", "男", 16));
personList.add(new Person("jerry", "女", 15));
personList.add(new Person("shuke", "男", 30));
personList.add(new Person("beita", "女", 26));
personList.add(new Person("damu", "男", 32));
// 1. 匿名内部类实现方式
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.getAge() - o2.getAge();
}
});
System.out.println(personList);
// 2. lambda表达式的实现方式
Collections.sort(personList, (p1, p2) -> p1.getAge() - p2.getAge());
// 3. 静态方法引用
Collections.sort(personList, Person::compareByAge);
// 4. 实例方法引用
PersonUtil pu = new PersonUtil();
Collections.sort(personList, pu::compareByName);
System.out.println("tom".hashCode());
System.out.println("jerry".hashCode());
System.out.println(personList);
// 5. 构造方法引用:绑定函数式接口
IPerson ip = Person::new;
Person person = ip.initPerson("jerry", "男", 22);
System.out.println(person);
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Person {
private String name; // 姓名
private String gender; // 性别
private int age; // 年龄
public static int compareByAge(Person p1, Person p2) {
return p1.getAge() - p2.getAge();
}
}
class PersonUtil {
// 增加一个实例方法
public int compareByName(Person p1, Person p2) {
return p1.getName().hashCode() - p2.getName().hashCode();
}
}
interface IPerson {
// 抽象方法:通过指定类型的构造方法初始化对象数据
Person initPerson(String name, String gender, int age);
}
package com.imooc.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.test Test2
* <p>Stream概述</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class Test2 {
public static void main(String[] args) {
// 1. 添加测试数据:存储多个账号的列表
List<String> accounts = new ArrayList<String>();
accounts.add("tom");
accounts.add("jerry");
accounts.add("beita");
accounts.add("shuke");
accounts.add("damu");
// 1.1. 业务要求:长度大于等于5的有效账号
for (String account : accounts) {
if (account.length() >= 5) {
System.out.println("有效账号:" + account);
}
}
// 1.2. 迭代方式进行操作
Iterator<String> it = accounts.iterator();
while(it.hasNext()) {
String account = it.next();
if (account.length() >= 5) {
System.out.println("it有效账号:" + account);
}
}
// 1.3. Stream结合lambda表达式,完成业务处理
List validAccounts = accounts.stream().filter(s->s.length()>=5).collect(Collectors.toList());
System.out.println(validAccounts);
}
}
package com.imooc.test;
import java.io.BufferedReader;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.imooc.test Test3
* <p>Stream常见操作API介绍
* 1. 聚合操作
*
* 2. stream的处理流程
* 数据源
* 数据转换
* 获取结果
* 3. 获取Stream对象
* 1. 从集合或者数组中获取[**]
* Collection.stream(),如accounts.stream()
* Collection.parallelStream()
* Arrays.stream(T t)
* 2. BufferReader
* BufferReader.lines()-> stream()
* 3. 静态工厂
* java.util.stream.IntStream.range()..
* java.nio.file.Files.walk()..
* 4. 自定构建
* java.util.Spliterator
* 5. 更多的方式..
* Random.ints()
* Pattern.splitAsStream()..
* 4. 中间操作API{intermediate}
* 操作结果是一个Stream,中间操作可以有一个或者多个连续的中间操作,需要注意的是,中间操作
* 只记录操作方式,不做具体执行,直到结束操作发生时,才做数据的最终执行。
* 中间操作:就是业务逻辑处理。
* 中间操作过程:无状态:数据处理时,不受前置中间操作的影响。
* map/filter/peek/parallel/sequential/unordered
* 有状态:数据处理时,受到前置中间操作的影响。
* distinct/sorted/limit/skip
* 5. 终结操作|结束操作{Terminal}
* 需要注意:一个Stream对象,只能有一个Terminal操作,这个操作一旦发生,就会真实处理数据,生成对应的处理结果。
* 终结操作:非短路操作:当前的Stream对象必须处理完集合中所有 数据,才能得到处理结果。
* forEach/forEachOrdered/toArray/reduce/collect/min/max/count/iterator
* 短路操作:当前的Stream对象在处理过程中,一旦满足某个条件,就可以得到结果。
* anyMatch/allMatch/noneMatch/findFirst/findAny等
* Short-circuiting,无限大的Stream-> 有限大的Stream。
* </p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class Test3 {}
package com.imooc.test;
import java.util.*;
import java.util.stream.Stream;
/**
* Copyright (C), 2018-2019, copyright info. DAMU., Ltd.
* FileName: com.imooc.text Test1
* <p>集合元素的常见操作</p>
*
* @author <a href="http://blog.csdn.net/muwenbin_flex">大牧莫邪</a>
* @version 1.00
*/
public class Test1 {
public static void main(String[] args) {
// 1. 批量数据 -> Stream对象
// 多个数据
Stream stream = Stream.of("admin", "tom", "damu");
// 数组
String [] strArrays = new String[] {"xueqi", "biyao"};
Stream stream2 = Arrays.stream(strArrays);
// 列表
List<String> list = new ArrayList<>();
list.add("少林");
list.add("武当");
list.add("青城");
list.add("崆峒");
list.add("峨眉");
Stream stream3 = list.stream();
// 集合
Set<String> set = new HashSet<>();
set.add("少林罗汉拳");
set.add("武当长拳");
set.add("青城剑法");
Stream stream4 = set.stream();
// Map
Map<String, Integer> map = new HashMap<>();
map.put("tom", 1000);
map.put("jerry", 1200);
map.put("shuke", 1000);
Stream stream5 = map.entrySet().stream();
// 2. Stream对象对于基本数据类型的功能封装
// int / long / double
// IntStream.of(new int[] {10, 20, 30}).forEach(System.out::println);
// IntStream.range(1, 5).forEach(System.out::println);
// IntStream.rangeClosed(1, 5).forEach(System.out::println);
// 3. Stream对象 --> 转换得到指定的数据类型
// 数组
// Object [] objx = stream.toArray(String[]::new);
// 字符串
// String str = stream.collect(Collectors.joining()).toString();
// System.out.println(str);
// 列表
// List<String> listx = (List<String>) stream.collect(Collectors.toList());
// System.out.println(listx);
// 集合
// Set<String> setx = (Set<String>) stream.collect(Collectors.toSet());
// System.out.println(setx);
// Map
// Map<String, String> mapx = (Map<String, String>) stream.collect(Collectors.toMap(x->x, y->"value:"+y));
// System.out.println(mapx);
// 4. Stream中常见的API操作
List<String> accountList = new ArrayList<>();
accountList.add("xongjiang");
accountList.add("lujunyi");
accountList.add("wuyong");
accountList.add("linchong");
accountList.add("luzhishen");
accountList.add("likui");
accountList.add("wusong");
// map() 中间操作,map()方法接收一个Functional接口
// accountList = accountList.stream().map(x->"梁山好汉:" + x).collect(Collectors.toList());
// filter() 添加过滤条件,过滤符合条件的用户
// accountList = accountList.stream().filter(x-> x.length() > 5).collect(Collectors.toList());
// forEach 增强型循环
// accountList.forEach(x-> System.out.println("forEach->" + x));
// accountList.forEach(x-> System.out.println("forEach->" + x));
// accountList.forEach(x-> System.out.println("forEach->" + x));
// peek() 中间操作,迭代数据完成数据的依次处理过程
// accountList.stream()
// .peek(x -> System.out.println("peek 1: " + x))
// .peek(x -> System.out.println("peek 2:" + x))
// .forEach(System.out::println);
// accountList.forEach(System.out::println);
// Stream中对于数字运算的支持
List<Integer> intList = new ArrayList<>();
intList.add(20);
intList.add(19);
intList.add(7);
intList.add(8);
intList.add(86);
intList.add(11);
intList.add(3);
intList.add(20);
// skip() 中间操作,有状态,跳过部分数据
// intList.stream().skip(3).forEach(System.out::println);
// limit() 中间操作,有状态,限制输出数据量
// intList.stream().skip(3).limit(2).forEach(System.out::println);
// distinct() 中间操作,有状态,剔除重复的数据
// intList.stream().distinct().forEach(System.out::println);
// sorted() 中间操作,有状态,排序
// max() 获取最大值
Optional optional = intList.stream().max((x, y)-> x-y);
System.out.println(optional.get());
// min() 获取最小值 类似 max()
// ……
// reduce() 合并处理数据
Optional optional2 = intList.stream().reduce((sum, x)-> sum + x);
System.out.println(optional2.get());
}
}
package com.imooc.performance;
import java.util.*;
public class Test {
public static void main(String[] args) {
Random random = new Random();
// 1. 基本数据类型:整数
// List<Integer> integerList = new ArrayList<Integer>();
//
// for(int i = 0; i < 1000000; i++) {
// integerList.add(random.nextInt(Integer.MAX_VALUE));
// }
//
// // 1) stream
// testStream(integerList);
// // 2) parallelStream
// testParallelStream(integerList);
// // 3) 普通for
// testForloop(integerList);
// // 4) 增强型for
// testStrongForloop(integerList);
// // 5) 迭代器
// testIterator(integerList);
// 2. 复杂数据类型:对象
List<Product> productList = new ArrayList<>();
for(int i = 0; i < 1000000; i++) {
productList.add(new Product("pro" + i, i, random.nextInt(Integer.MAX_VALUE)));
}
// 调用执行
testProductStream(productList);
testProductParallelStream(productList);
testProductForloop(productList);
testProductStrongForloop(productList);
testProductIterator(productList);
}
public static void testStream(List<Integer> list) {
long start = System.currentTimeMillis();
Optional optional = list.stream().max(Integer::compare);
System.out.println(optional.get());
long end = System.currentTimeMillis();
System.out.println("testStream:" + (end - start) + "ms");
}
public static void testParallelStream(List<Integer> list) {
long start = System.currentTimeMillis();
Optional optional = list.parallelStream().max(Integer::compare);
System.out.println(optional.get());
long end = System.currentTimeMillis();
System.out.println("testParallelStream:" + (end - start) + "ms");
}
public static void testForloop(List<Integer> list) {
long start = System.currentTimeMillis();
int max = Integer.MIN_VALUE;
for(int i = 0; i < list.size(); i++) {
int current = list.get(i);
if (current > max) {
max = current;
}
}
System.out.println(max);
long end = System.currentTimeMillis();
System.out.println("testForloop:" + (end - start) + "ms");
}
public static void testStrongForloop(List<Integer> list) {
long start = System.currentTimeMillis();
int max = Integer.MIN_VALUE;
for (Integer integer : list) {
if(integer > max) {
max = integer;
}
}
System.out.println(max);
long end = System.currentTimeMillis();
System.out.println("testStrongForloop:" + (end - start) + "ms");
}
public static void testIterator(List<Integer> list) {
long start = System.currentTimeMillis();
Iterator<Integer> it = list.iterator();
int max = it.next();
while(it.hasNext()) {
int current = it.next();
if(current > max) {
max = current;
}
}
System.out.println(max);
long end = System.currentTimeMillis();
System.out.println("testIterator:" + (end - start) + "ms");
}
public static void testProductStream(List<Product> list) {
long start = System.currentTimeMillis();
Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
System.out.println(optional.get());
long end = System.currentTimeMillis();
System.out.println("testProductStream:" + (end - start) + "ms");
}
public static void testProductParallelStream(List<Product> list) {
long start = System.currentTimeMillis();
Optional optional = list.stream().max((p1, p2)-> p1.hot - p2.hot);
System.out.println(optional.get());
long end = System.currentTimeMillis();
System.out.println("testProductParallelStream:" + (end - start) + "ms");
}
public static void testProductForloop(List<Product> list) {
long start = System.currentTimeMillis();
Product maxHot = list.get(0);
for(int i = 0; i < list.size(); i++) {
Product current = list.get(i);
if (current.hot > maxHot.hot) {
maxHot = current;
}
}
System.out.println(maxHot);
long end = System.currentTimeMillis();
System.out.println("testProductForloop:" + (end - start) + "ms");
}
public static void testProductStrongForloop(List<Product> list) {
long start = System.currentTimeMillis();
Product maxHot = list.get(0);
for (Product product : list) {
if(product.hot > maxHot.hot) {
maxHot = product;
}
}
System.out.println(maxHot);
long end = System.currentTimeMillis();
System.out.println("testProductStrongForloop:" + (end - start) + "ms");
}
public static void testProductIterator(List<Product> list) {
long start = System.currentTimeMillis();
Iterator<Product> it = list.iterator();
Product maxHot = it.next();
while(it.hasNext()) {
Product current = it.next();
if (current.hot > maxHot.hot) {
maxHot = current;
}
}
System.out.println(maxHot);
long end = System.currentTimeMillis();
System.out.println("testProductIterator:" + (end - start) + "ms");
}
}
class Product {
String name; // 名称
Integer stock; // 库存
Integer hot; // 热度
public Product(String name, Integer stock, Integer hot) {
this.name = name;
this.stock = stock;
this.hot = hot;
}
}
package com.imooc.performance;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Test2 {
public static void main(String[] args) {
// 整数列表
List<Integer> lists = new ArrayList<Integer>();
// 增加数据
for (int i = 0; i < 1000; i++){
lists.add(i);
}
// 串行Stream
List<Integer> list2 = new ArrayList<>();
lists.stream().forEach(x->list2.add(x));
System.out.println(lists.size());
System.out.println(list2.size());
// 并行Stream
List<Integer> list3 = new ArrayList<>();
lists.parallelStream().forEach(x-> list3.add(x));
System.out.println(list3.size());
List<Integer> list4 = lists.parallelStream().collect(Collectors.toList());
System.out.println(list4.size());
}
}