package com.fhc.modules.api.utils;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* lambda Test
*/
public class java8lambda {
public static void main(String[] args) {
/** 使用Lambda表达式和函数接口 */
List languages = Arrays.asList("Python", "Java", "C++", "JavaScript", "Vue");
System.out.println("Languages which starts with J:");
filter(languages, str -> str.toString().startsWith("J"));
System.out.println("Languages whiche end with a");
filter(languages, str -> str.toString().endsWith("a"));
/** 复杂的结合Predicate使用 */
System.out.println("Languages whiche starts with J and end with a:");
Predicate startWithJ = str -> str.toString().startsWith("J");
Predicate endWithJ = str -> str.toString().endsWith("a");
filter(languages, startWithJ.and(endWithJ)); // 等价于下
filter(languages, str -> str.toString().startsWith("J") && str.toString().endsWith("a"));
System.out.println("Languages whiche starts with J or end with a:");
filter(languages, startWithJ.or(endWithJ)); // 等价于下
filter(languages, str -> str.toString().startsWith("J") || str.toString().endsWith("e"));
/** 使用Lambda 实现 Map 和 Reduce */
System.out.println("使用Lambda 实现 Map 和 Reduce ");
List constBeforeTax = Arrays.asList(100, 200, 300, 400, 500, 400);
for (Integer cost : constBeforeTax) {
double price = cost +.12 * cost;
System.out.println(price);
}
System.out.println("总个数:" + constBeforeTax.stream().count());
System.out.println("去重后个数:" + constBeforeTax.stream().distinct().count());
System.out.println("取第一个:" + constBeforeTax.stream().findFirst().get());
constBeforeTax.stream().map(cost -> cost +.12 * cost).forEach(System.out::println);
// reduce()是将集合中所有值结合进一个,Reduce类似SQL语句中的sum(),avg()或count()
System.out.println("Toal:" + constBeforeTax.stream().map(cost -> cost +.12 * cost).reduce((sum, cost) -> sum + cost).get());
// System.out.println("Toal:" + constBeforeTax.stream().map(cost -> cost + .12 * cost).reduce((, cost) -> avg).get());
/** 通过filter创建一个字符串String的集合 */
List filterStr = languages.stream().filter(str -> str.toString().startsWith("J") || str.toString().endsWith("e")).collect(Collectors.toList());
filter(filterStr, str ->true);
/** 对集合中每个元素应用函数 */
String filterString = filterStr.stream().map(str -> str.toUpperCase()).collect(Collectors.joining(","));
System.out.println(filterString);
/** sum 、avg 、max 、min */
List primes = Arrays.asList(2, 3, 4, 5, 6, 7, 8, 9);
IntSummaryStatistics intSummaryStatistics = primes.stream().mapToInt(s -> s).summaryStatistics();
System.out.println("sum:" + intSummaryStatistics.getSum() +"\navg:" + intSummaryStatistics.getAverage() +"\nmax:" + intSummaryStatistics.getMax() +"\nmin:" + intSummaryStatistics.getMin());
System.out.println(primes.parallelStream().mapToInt(s -> s).sum());
/** 排序 */
String[] names = {"Python", "Java", "C++", "JavaScript", "Vue"};
Arrays.sort(names, new Comparator() {
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
});
Arrays.sort(names, (String s1, String s2) -> s1.compareTo(s2));
}
public static void filter(List names, Predicate condition) {
names.forEach(name -> {
if (condition.test(name)) System.out.print(name +"|||");
});
System.out.println();
}
}
package com.example.demo.test;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author :suyl
* @date :Created in 2020/9/3 9:06
* @description:
* @version: 1.0
*/
public class Java8Stream {
static List<Apple> appleList = new ArrayList<>();//存放apple对象集合
static {
Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10);
Apple apple12 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20);
Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30);
Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);
}
public static void main(String[] args) {
// 1.分组 List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
System.err.println("groupBy:" + groupBy);
// 2.list转Map id为key,apple对象为value,可以这么做:
/**
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
*/
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
// 3.过滤Filter 过滤出符合条件的数据
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
System.err.println("filterList:" + filterList);
// 4.求和 计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:" + totalMoney); //totalMoney:17.48
// 5、查找流中最大 最小值
// Collectors.maxBy 和 Collectors.minBy 来计算流中的最大或最小值。
Optional<Apple> maxDish = appleList.stream().
collect(Collectors.maxBy(Comparator.comparing(Apple::getMoney)));
maxDish.ifPresent(System.out::println);
Optional<Apple> minDish = appleList.stream().
collect(Collectors.minBy(Comparator.comparing(Apple::getMoney)));
minDish.ifPresent(System.out::println);
// 6.去重 根据id去重
List list = new ArrayList();
List uniqueStr = (List) list.stream().distinct().collect(Collectors.toList());
appleList = appleList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Apple::getId))), ArrayList::new)
);
System.out.println();
appleList.stream().filter(s -> {
System.out.println(s.toString());
return true;
}).collect(Collectors.toList());
}
}
@Data
@AllArgsConstructor
class Apple {
private Integer id;
private String name;
private BigDecimal money;
private Integer num;
}