# Map

## compute

``V compute(K key, BiFunction < ? super K, ? super V, ? extends V> remappingFunction)``

``````public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
map.compute("1", (k,v)-> {
System.out.println("key = " + k + ", value = " + v);
if (v != null) {
return v+1;
} else {
return 0;
}
});
map.compute("3", (k,v)->{
System.out.println("key = " + k + ", value = " + v);
if (v != null) {
return v+1;
} else {
return 0;
}
});
System.out.println(map.toString());
}``````

``````key = 1, value = 1
key = 3, value = null
{1=2, 2=2, 3=0}``````

## computeIfAbsent

``V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)``

computeIfAbsent的方法有两个参数 第一个是所选map的key，第二个是需要做的操作。这个方法当key值不存在时才起作用。

``````public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
// key存在返回value
Integer integer1 = map.computeIfAbsent("2", key -> new Integer(10));
// key不存在执行函数存入
Integer integer2 = map.computeIfAbsent("3", key -> new Integer(20));
System.out.println("integer1 = " + integer1);
System.out.println("integer2 = " + integer2);
System.out.println(map.toString());
}``````

``````integer1 = 2
integer2 = 20
{1=1, 2=2, 3=20}``````

## computeIfPresent

``V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)``

``````public static void main(String[] args) {
HashMap<String,Integer> map = new HashMap<>();
map.put("1",1);
map.put("2",2);
map.put("3",3);
// 只对 map 中存在的key对应的value进行操作
Integer integer1 = map.computeIfPresent("3", (k,v) -> {
System.out.println("key = " + k + ", value = " + v);
return v+1;
});
Integer integer2 = map.computeIfPresent("4", (k,v) -> {
System.out.println("key = " + k + ", value = " + v);
return v+1;
} );
System.out.println("integer1 = " + integer1);
System.out.println("integer2 = " + integer2);
System.out.println(map.toString());
}``````

``````key = 3, value = 3
integer1 = 4
integer2 = null
{1=1, 2=2, 3=4}``````

# Optional

of(T value)

``````Student student = new Student();
// 如果 student 为 null，则会抛出NullPointerException
// 适用于 student 不为空的情况
Optional<Student> opt = Optional.of(student);``````

ofNullable(T value)

``````Student student = new Student();
// student 为 null 时不会报错
Optional<User> opt = Optional.ofNullable(user);
// 若 student 不为空，则返回true，否则返回false
System.out.println(opt.isPresent());``````

## 获取对象值

``````Student student = new Student();
// student 为 null 时不会报错
Optional<User> opt = Optional.ofNullable(user);
// 若 student 不为空，则返回true，否则返回false
System.out.println(opt.isPresent());
// 若 student 为 null， opt.get() 会报错
// 若 student 不为null，则返回对象值
System.out.println(opt.get());``````

``````Student student = new Student();
Optional<Student> opt = Optional.ofNullable(student);
// 只有当 student 不为空时才会执行 ifPresent 方法里面的表达式
opt.ifPresent(u -> {
});``````

## 返回默认值

orElse(T other)

``````Student student1 = null;
Student student2 = new Student();
Student optStudent = Optional.ofNullable(student1).orElse(student2);

``````Student student1 = new Student();
Student student2 = new Student();
Student optStudent = Optional.ofNullable(student1).orElse(student2);

orElseGet(Supplier<? extends T> other)

``````Student student1 = new Student();
Student optStudent = Optional.ofNullable(student1).orElseGet(()->{
Student student2 = new Student();
return student2;
});
// 如果 student1 为 null，控制台则打印 "lzc" ，否则打印 "lizhencheng"

orElse() 和 orElseGet() 的不同之处

``````public class Main {
public static void main(String[] args) {
Student student1 = new Student();

System.out.println("orElse......");
Student optStudent1 = Optional.ofNullable(student1).orElse(createNewStudent());
System.out.println("orElseGet......");
Student optStudent2 = Optional.ofNullable(student1).orElseGet(()-> createNewStudent());

}

public static Student createNewStudent() {
System.out.println("createNewStudent......");
Student student = new Student();
return student;
}
}``````

``````orElse......
createNewStudent......
orElseGet......
lzc
lzc``````

## 返回异常

``````Student student = null;
Student optStudent = Optional.ofNullable(student).orElseThrow(() -> new IllegalArgumentException("参数不能为空"));``````

## 转换值

``````Student student = new Student("lzc","1班");
String str = Optional
.ofNullable(student)
.orElse("lizhencheng");
System.out.println(str);``````

## 过滤值

``````Student student = new Student("lzc","1班");
Optional<Student> temp = Optional
.ofNullable(student)
System.out.println(temp.isPresent());``````

# Stream

## forEach

``default void forEach(Consumer<? super T> action)``

``````List<String> list = new ArrayList<>();
list.forEach(s -> System.out.println(s));``````

## filter

``Stream<T> filter(Predicate<? super T> predicate)``
``````List<String> list = new ArrayList<>();
List<String> resultList = list
.stream()
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
resultList.forEach(s -> System.out.println(s));``````

Collectors.toList()可以把流转换为 List 类型或者是Set类型

## distinct

``Stream<T> distinct()``

``````List<String> list = new ArrayList<>();
List<String> resultList = list
.stream()
.distinct()
.collect(Collectors.toList());
resultList.forEach(s -> System.out.println(s));``````

## sorted

``````Stream<T> sorted()

Stream<T> sorted(Comparator<? super T> comparator)``````

``````List<Student> list = new ArrayList<>();

List<Student>  resultList = list
.stream()
.sorted((s1,s2) -> s1.getAge() - s2.getAge())
.collect(Collectors.toList());

resultList.forEach(s -> System.out.println(s.toString()));``````

``````List<Student> list = new ArrayList<>();

List<Student>  resultList = list
.stream()
//.sorted(Comparator.comparing(Student::getAge)) // 升序
.sorted(Comparator.comparing(Student::getAge).reversed()) // 降序
.collect(Collectors.toList());

resultList.forEach(s -> System.out.println(s.toString()));``````

## limit

``Stream<T> limit(long maxSize)``

``````List<Student> list = new ArrayList<>();

List<Student>  resultList = list
.stream()
.limit(2)
.collect(Collectors.toList());

resultList.forEach(s -> System.out.println(s.toString()));``````

## skip

``Stream<T> skip(long n)``

``````List<Student> list = new ArrayList<>();

List<Student>  resultList = list
.stream()
.skip(2)
.collect(Collectors.toList());

resultList.forEach(s -> System.out.println(s.toString()));``````

## map

``<R> Stream<R> map(Function<? super T, ? extends R> mapper)``

``````List<Student> list = new ArrayList<>();

List<String>  resultList = list
.stream()
.map(s -> {
}).collect(Collectors.toList());

resultList.forEach(s -> System.out.println(s.toString()));``````

## flatMap

``<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)``

``````List<String> list = new ArrayList<>();

List<String> resultList = list
.stream()
.map(s -> s.split(" "))
.flatMap(Arrays::stream).collect(Collectors.toList());

resultList.stream().forEach(s -> System.out.println(s));``````

## anyMatch

``boolean anyMatch(Predicate<? super T> predicate)``

``````List<Student> list = new ArrayList<>();
// 是否存在一个 Student 对象的 age >= 20
boolean b = list.stream().anyMatch(s -> s.getAge() >= 20);
System.out.println(b);``````

## allMatch

``boolean allMatch(Predicate<? super T> predicate)``

## collect

``<R, A> R collect(Collector<? super T, A, R> collector)``

### joining

joining 连接字符串

``````List<String> list = new ArrayList<>();
String collect = list.stream().collect(Collectors.joining(","));
System.out.println(collect);``````

### toList/toSet

toList或者toSet，将数据流转换成List类型或者是Set类型

``````List<String> list = new ArrayList<>();
List<String> resultList = list
.stream()
.filter(s -> s.length() > 3)
.collect(Collectors.toList());
resultList.forEach(s -> System.out.println(s));``````

### groupingBy

groupingBy 用于将数据分组，最终返回一个 Map 类型

``````List<Student> list = new ArrayList<>();

Map<Integer, List<Student>> collect =
list.stream()
// .collect(Collectors.groupingBy(Student::getAge)); // 这样是无序的
// .collect(Collectors.groupingBy(Student::getAge, TreeMap::new,Collectors.toList())); // 升序
.collect(Collectors.groupingBy(Student::getAge, (() -> new TreeMap().descendingMap()),Collectors.toList())); // 降序

for (Integer key : collect.keySet()) {
List<Student> students = collect.get(key);
System.out.println("age = " + key);
students.forEach(s -> System.out.println(s.toString()));
}``````

groupingBy 可以接受一个第二参数实现多级分组：

``````Map<Integer, Map<String, List<Student>>> collect =
list.stream()
.collect(
Collectors.groupingBy(
Student::getAge,
)
);``````

``list.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.summingInt(Student::getAge)));``

### partitioningBy

``Map<Boolean, List<Student>> collect = list.stream().collect(Collectors.partitioningBy(s -> s.getAge() > 1));``

partitioningBy 也可以添加一个收集器作为第二参数，进行类似 groupBy 的多重分区等等操作。

(=￣ω￣=)··· 暂无内容！

40

4

4

4