package daily_test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Collectors;
public class Test2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(50);
list.add(60);
list.add(60);
list.add(90);
Integer result;
// 去重
/** records.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(asus ->
asus.getBydpartno() + "" + asus.getAsuspartno() + "," + asus.getAsusnextpartno()
))), ArrayList::new)) */;
/** 求最大值*/
Optional<Integer> optional = list.stream().max(Comparator.comparingInt(Integer::intValue));
result = optional.orElse(null);
System.out.println("求最大值(1):" + result);
Optional<Integer> optional1 = list.stream().max((o1, o2) -> o1 - o2);
result = optional1.orElse(null);
System.out.println("求最大值(2):" + result);
// mapToInt 返回的是数值流 IntStream。 mapToDouble, mapToLong
OptionalInt optionalInt = list.stream().mapToInt(Integer::intValue).max();
result = optionalInt.orElse(0);
System.out.println("求最大值(3):" + result);
/** 求和 */
result = list.stream().reduce(0, (integer1, integer2) -> integer1 + integer2);
System.out.println("求和(1):" + result);
result = list.stream().reduce(0, Integer::sum);
System.out.println("求和(2):" + result);
/** 过滤 filter(Predicate) filter返回的是条件判断中结果为true,并非是过滤掉 */
result = list.stream().filter(integer4 -> integer4 == 50).findFirst().orElse(0);
System.out.println("刷选符合条件的:" + result);
/** 去重 */
List<Integer> newList = list.stream().distinct().collect(Collectors.toList());
/** 截取流前 N 个元素 limit(N) */
newList = list.stream().limit(2).collect(Collectors.toList());
/** 排除流的前 N 个元素 skip(N) */
newList = list.stream().skip(2).collect(Collectors.toList());
/** 流中是否包含 x 这个元素 anyMatch(element -> element.equals(x) || element == x) */
boolean flag = list.stream().anyMatch(integer -> integer == 50);
/** 从流中获取随机元素 findAny() */
Optional<Integer> any = list.stream().findAny();
result = any.orElse(0);
/**
* Optional 用于防止出现NullpointException
*
* isPresent()
* 判断容器中是否有值
*
* ifPresent(Consume lambda)
* 容器若不为空则执行括号中的Lambda表达式。
*
* T get()
* 获取容器中的元素,若容器为空则抛出NoSuchElement异常。
*
* T orElse(T other)
* 获取容器中的元素,若容器为空则返回括号中的默认值。
*/
Optional<Integer> optional3 = list.stream().max((o1, o2) -> o1 - o2);
// 1
result = optional3.isPresent() ? optional3.get() : null;
// 2
result = optional3.orElse(null);
// 上面的 1 和 2 是等价的
}
}