1 不可变集合

1.1 概念

  • 不可变集合,就是不可被修改的集合。
  • 集合的数据项在创建的时候提供,并且在整个生命周期中都不可改变,否则报错。

    1.2 作用

  • 如果某个数据不能被修改,把它防御性地拷贝到不可变集合中是个很好的实践。

  • 或者当集合对象被不可信的库调用时,不可变形式是安全的。

    1.3 创建不可变集合

  • 在List、Set、Map接口中,都存在of方法,可以创建一个不可变的集合。【jdk9】

image.png

  • 这个集合不能添加,不能删除,不能修改。

示例:

  1. public static void main(String[] args) {
  2. // 1、不可变的List集合
  3. List<Double> lists = List.of(569.5, 700.5, 523.0, 570.5);
  4. // lists.add(689.0);
  5. // lists.set(2, 698.5);
  6. // System.out.println(lists);
  7. double score = lists.get(1);
  8. System.out.println(score);
  9. // 2、不可变的Set集合
  10. Set<String> names = Set.of("迪丽热巴", "迪丽热九", "马尔扎哈", "卡尔眨巴" );
  11. // names.add("三少爷");
  12. System.out.println(names);
  13. // 3、不可变的Map集合
  14. Map<String, Integer> maps = Map.of("huawei",2, "Java开发", 1 , "手表", 1);
  15. // maps.put("衣服", 3);
  16. System.out.println(maps);
  17. }

2 Sream流

2.1 概念

  • 在Java 8中,得益于Lambda所带来的函数式编程, 引入了一个全新的Stream流概念。
  • 目的:用于简化集合和数组操作的API。
  • 结合了lamda表达式

stream流程的思想

  • 先得到集合或者数组的Stream流(就是一根传送带)。
  • 把元素放上去。
  • 然后就用这个Stream流简化的API来方便的操作元素

2.2 获取stream流

2.2.1 集合获取sream流

可以使用Collection接口中的默认方法stream()生成流:default Stream stream()

2.2.2 数组获取sream流

Arrays.stream(数组) / Stream.of(数组);

public static Stream stream(T[] array) 获取当前数组的Stream流
public static Stream of(T… values) 获取当前数组/可变数据的Stream流

2.2.3 示例

2.3 中间方法

filter(Predicate predicate) 用于对流中的数据进行过滤,取满足true的数据。
limit(long maxSize) 截取前指定参数个数的数据
skip(long n) 跳过指定参数个数的数据,返回由该流的剩余元素组成的流
concat(Stream a, Stream b) 合并a和b两个流为一个流
distinct() 返回由该流的不同元素(根据Object.equals(Object) )组成的流
sorted() 返回由此流的元素组成的流,根据自然顺序排序
sorted(Comparator c) 回由该流的元素组成的流,根据提供的Comparator进行排序
map(Function mapper) 返回由给定函数应用于此流的元素的结果组成的流
flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
mapToInt(ToIntFunction mapper) 返回一个IntStream其中包含将给定函数应用于此流的元素的结果
peek 如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。

注意:

  • 中间方法也称为非终结方法,调用完成后返回新的Stream流可以继续使用,支持链式编程。
  • 在Stream流中无法直接修改集合、数组中的数据。

2.3.1 flatMap方法

  1. Stream<String> s3 = list.stream().flatMap(s -> {
  2. //将每个元素转换成一个stream
  3. String[] split = s.split(",");
  4. Stream<String> s2 = Arrays.stream(split);
  5. return s2;
  6. })

2.3.2 peek消费方法

Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);

studentList.stream()
    .peek(o -> o.setAge(100))
    .forEach(System.out::println);

//结果:
Student{name='aa', age=100}
Student{name='bb', age=100}

2.4 终结方法

2.4.1 匹配、聚合操作

allMatch 接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false
noneMatch 接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false
anyMatch 接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
findFirst 返回流中第一个元素
findAny 返回流中的任意元素
count 返回流中元素的总个数
max 返回流中元素最大值
min 返回流中元素最小值

示例:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

boolean allMatch = list.stream().allMatch(e -> e > 10); //false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
boolean anyMatch = list.stream().anyMatch(e -> e > 4); //true

Integer findFirst = list.stream().findFirst().get(); //1
Integer findAny = list.stream().findAny().get(); //1

long count = list.stream().count(); //5
Integer max = list.stream().max(Integer::compareTo).get(); //5
Integer min = list.stream().min(Integer::compareTo).get(); //1

2.4.2 规约操作

  1. Optional reduce(BinaryOperator accumulator):第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
  2. T reduce(T identity, BinaryOperator accumulator):流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
  3. U reduce(U identity,BiFunction accumulator,BinaryOperator combiner):在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。 ```java //经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16 List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                               11, 12, 13, 14, 15, 16, 17, 18, 19, 
                               20, 21, 22, 23, 24);
    

Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get(); System.out.println(v); // 300

Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2); System.out.println(v1); //310

// chuan Integer v2 = list.stream().reduce(0, (x1, x2) -> { System.out.println(“stream accumulator: x1:” + x1 + “ x2:” + x2); return x1 - x2; }, (x1, x2) -> { System.out.println(“stream combiner: x1:” + x1 + “ x2:” + x2); return x1 * x2; }); System.out.println(v2); // -300

Integer v3 = list.parallelStream().reduce(0, (x1, x2) -> { System.out.println(“parallelStream accumulator: x1:” + x1 + “ x2:” + x2); return x1 - x2; }, (x1, x2) -> { System.out.println(“parallelStream combiner: x1:” + x1 + “ x2:” + x2); return x1 * x2; }); System.out.println(v3); //197474048

| void forEach(Consumer action) | 对此流的每个元素执行遍历操作 |
| --- | --- |
| long count() | 返回此流中的元素数 |

**注意:**

- 终结操作方法,调用完成后流就无法继续使用了,原因是不会返回Stream了。
- **终结方法后流不可以继续使用,非终结方法会返回新的流,支持链式编程。**

<a name="VC2oB"></a>
## 2.5 收集操作
 collect:接收一个Collector实例,将流中元素收集成另外一个数据结构。<br /> Collector<T, A, R> 是一个接口,有以下5个抽象方法:

- Supplier<A> supplier():创建一个结果容器A
- BiConsumer<A, T> accumulator():消费型接口,第一个参数为容器A,第二个参数为流中元素T。
- BinaryOperator<A> combiner():函数接口,该参数的作用跟上一个方法(reduce)中的combiner参数一样,将并行流中各 个子进程的运行结果(accumulator函数操作后的容器A)进行合并。
- Function<A, R> finisher():函数式接口,参数为:容器A,返回类型为:collect方法最终想要的结果R。
- Set<Characteristics> characteristics():返回一个不可变的Set集合,用来表明该Collector的特征。有以下三个特征:
   - CONCURRENT:表示此收集器支持并发。(官方文档还有其他描述,暂时没去探索,故不作过多翻译)
   - UNORDERED:表示该收集操作不会保留流中元素原有的顺序。
   - IDENTITY_FINISH:表示finisher参数只是标识而已,可忽略。

示例:
```java
Student s1 = new Student("aa", 10,1);
Student s2 = new Student("bb", 20,2);
Student s3 = new Student("cc", 10,3);
List<Student> list = Arrays.asList(s1, s2, s3);

//装成list
List<Integer> ageList = list.stream().map(Student::getAge)
    .collect(Collectors.toList()); // [10, 20, 10]

//转成set
Set<Integer> ageSet = list.stream().map(Student::getAge)
    .collect(Collectors.toSet()); // [20, 10]

//转成map,注:key不能相同,否则报错
Map<String, Integer> studentMap = list.stream()
    .collect(Collectors.toMap(Student::getName, Student::getAge)); 
// {cc=10, bb=20, aa=10}

//字符串分隔符连接
String joinName = list.stream().map(Student::getName)
    .collect(Collectors.joining(",", "(", ")")); 
// (aa,bb,cc)

//聚合操作
//1.学生总数
Long count = list.stream().collect(Collectors.counting()); // 3
//2.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(Student::getAge)
    .collect(Collectors.maxBy(Integer::compare)).get(); // 20
//3.所有人的年龄
Integer sumAge = list.stream()
    .collect(Collectors.summingInt(Student::getAge)); // 40
//4.平均年龄
Double averageAge = list.stream()
    .collect(Collectors.averagingDouble(Student::getAge)); 
// 13.333333333333334

// 带上以上所有方法
DoubleSummaryStatistics statistics = list.stream()
    .collect(Collectors.summarizingDouble(Student::getAge));
System.out.println("count:" + statistics.getCount() 
                   + ",max:" + statistics.getMax() 
                   + ",sum:" + statistics.getSum() 
                   + ",average:" 
                   + statistics.getAverage());

//分组
Map<Integer, List<Student>> ageMap = list.stream()
    .collect(Collectors.groupingBy(Student::getAge));

//多重分组,先根据类型分再根据年龄分
Map<Integer, Map<Integer, List<Student>>> typeAgeMap = list.stream()
    .collect(Collectors.groupingBy(Student::getType,
                                   Collectors.groupingBy(Student::getAge)));

//分区
//分成两部分,一部分大于10岁,一部分小于等于10岁
Map<Boolean, List<Student>> partMap = list.stream()
    .collect(Collectors.partitioningBy(v -> v.getAge() > 10));

//规约
Integer allAge = list.stream().map(Student::getAge)
    .collect(Collectors.reducing(Integer::sum)).get(); 
//40