Create immutable collections and use of Stream

I can't find the answer, trying to find myself

 1. Create immutable collections

Immutable collections: collections that cannot be modified (the length cannot be modified, the content cannot be modified)

Application Scenario

  • If some data cannot be modified, it is good practice to defensively copy it into an immutable collection.
  • The immutable form is safe when collection objects are called by untrusted libraries. Simple understanding: do not want others to modify the content in the collection (for example, the cards of Doudizhu are fixed)

Writing format for creating immutable collections

In the List, Set, and Map interfaces, there are static of methods that can obtain an immutable collection.

Example of creating an immutable List collection

import java.util.List;

/**
 * @Description: 不可变ListDemo
 * @author: lh
 * @date: 2023年04月09日 20:36
 */
public class ImmutableList {
    public static void main(String[] args) {
        // 创建不可变的List集合
        List<String> list = List.of("路明非", "诺诺师姐", "凯撒", "面瘫师兄");

        // 打印List集合
        for (String s : list) {
            System.out.println(s);
        }

        // 测试往不可变的list中添加数据
        list.add("格里芬");
    }
}

output result

路明非
诺诺师姐
凯撒
面瘫师兄
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:76)
	at org.zto.immutable.ImmutableList.main(ImmutableList.java:21)

 Example of creating an immutable Set collection

import java.util.Set;

/**
 * @Description: 不可变SetDemo
 * @author: lh
 * @date: 2023年04月10日 20:33
 */
public class ImmutableSet {
    public static void main(String[] args) {
        // 创建不可变的Set集合
        Set<String> set = Set.of("路明非", "诺诺师姐", "凯撒", "面瘫师兄");

        // 打印set集合
        for (String s : set) {
            System.out.println(s);
        }

        // 测试移除不可变集合的元素
        set.remove("路明非");
    }
}

 output result

路明非
面瘫师兄
凯撒
诺诺师姐
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.remove(ImmutableCollections.java:79)
	at org.zto.immutable.ImmutableSet.main(ImmutableSet.java:21)

Example of creating an immutable Map collection

import java.util.Map;
import java.util.Set;

/**
 * @Description: 不可变MapDemo
 * @author: lh
 * @date: 2023年04月10日 20:38
 */
public class ImmutableMap {
    public static void main(String[] args) {
        // 创建不可变的Map集合
        Map<String, String> map = Map.of("路明非", "1", "诺诺师姐", "2", "凯撒", "3", "面瘫师兄", "4");

        // 打印List集合
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key + "=" + map.get(key));
        }

        // 测试往不可变的Map中添加数据
        map.put("校长", "5");
    }
}

output result

凯撒=3
面瘫师兄=4
路明非=1
诺诺师姐=2
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
	at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:731)
	at org.zto.immutable.ImmutableMap.main(ImmutableMap.java:24)

 Notice

  • The keys in the map cannot be repeated
  • The of method in the map has an upper limit for parameters, and can only pass up to 10 key-value pairs

 Immutable Map - pass multiple parameters

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Description: 不可变MapDemo - 多参数
 * @author: lh
 * @date: 2023年04月10日 21:00
 */
public class ImmutableMapCopy {
    public static void main(String[] args) {
        // 创建超过10个参数的map集合
        HashMap<String, String> hm = new HashMap<>();
        hm.put("1", "汉族");
        hm.put("2", "壮族");
        hm.put("3", "满族");
        hm.put("4", "回族");
        hm.put("5", "苗族");
        hm.put("6", "维吾尔族");
        hm.put("7", "土家族");
        hm.put("8", "彝族");
        hm.put("9", "蒙古族");
        hm.put("10", "藏族");
        hm.put("11", "布依族");

        // 创建不可变集合 - java 1.8
        Map map8 = Map.ofEntries(hm.entrySet().toArray(new Map.Entry[0]));
        Set entried = map8.entrySet();
        for (Object en : entried) {
            System.out.println(en);
        }

        System.out.println("==================");

        // 创建不可变集合 - java 11
        Map<String, String> map11 = Map.copyOf(hm);
        Set<Map.Entry<String, String>> entries = map11.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            System.out.println(entry);
        }

        System.out.println("====================");
        System.out.println(map11.get("1"));
    }
}

output result

1=汉族
11=布依族
2=壮族
3=满族
4=回族
5=苗族
6=维吾尔族
7=土家族
8=彝族
9=蒙古族
10=藏族
==================
1=汉族
11=布依族
2=壮族
3=满族
4=回族
5=苗族
6=维吾尔族
7=土家族
8=彝族
9=蒙古族
10=藏族
====================
汉族

 Summary of immutable collections

  1. After the characteristics of immutable collections are defined, they cannot be modified, added or deleted
  2. How to create an immutable collection List, Set, and Map interfaces all have the of method to create an immutable collection
  3. Details of the three ways
  • List: use directly

  • Set: elements cannot be repeated

  • Map: elements cannot be repeated, and the number of key-value pairs is at most 10. If more than 10, use the ofEntries method (java8)

    Use the copyOf method (java11)

2. Stream

example

有下面的这个list
List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("张三丰");
        list.add("张芷若");
        list.add("张三");
        list.add("金毛狮王");
        
 1. 把所有以"张"开头的元素存储到新集合中
 2. 把"张"开头且长度为3的元素存储到新集合中
 3. 遍历打印最终的结果

Method 1: Traditional for loop traversal method

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: stream初体验
 * @author: lh
 * @date: 2023年04月10日 21:45
 */
public class streamDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("张三丰");
        list.add("张芷若");
        list.add("张三");
        list.add("金毛狮王");

        // 1. 把所有以"张"开头的元素存储到新集合中
        List<String> list1 = new ArrayList<>();
        for (String name : list) {
            if (name.startsWith("张")) {
                list1.add(name);
            }
        }

        // 2. 把"张"开头且长度为3的元素存储到新集合中
        List<String> list2 = new ArrayList<>();
        for (String name : list1) {
            if (name.length() == 3)
            {
                list2.add(name);
            }
        }

        // 3. 遍历打印最终的结果
        System.out.println(list2);
    }
}

 output result

[张无忌, 张三丰, 张芷若]

Method 2: use stream flow

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: stream初体验
 * @author: lh
 * @date: 2023年04月10日 21:45
 */
public class streamDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("张无忌");
        list.add("张三丰");
        list.add("张芷若");
        list.add("张三");
        list.add("金毛狮王");

        list.stream().filter(name -> name.startsWith("张")).filter(name -> name.length() == 3).forEach(System.out::println);
    }
}

 output result

张无忌
张三丰
张芷若

The function and usage steps of stream

The role of the stream

Combining Lambda expressions to simplify operations on collections and arrays.

Steps to use the stream

  1. First get a Stream (pipeline) and put the data on it.
  2. Use the API in the stream to perform various operations
    • Intermediate method: After the filtering and conversion methods are called, other methods can also be called
    • Termination method: the last step of statistics and printing. After the call is completed, other methods cannot be called

Intermediate method of stream

Points to note:

  • The intermediate method returns a new stream, the original stream can only be used once, it is recommended to use chain programming
  • Modifying the data in the stream will not affect the data in the original collection or array

The finalization method of the stream

 practise

 Exercise 1 - Numeric Filtering

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 数字过滤
 * @author: lh
 * @date: 2023年04月11日 20:04
 */
public class Demo1 {
    /*
     * 定义一个集合,并添加一些整数 1,2,3,4,5,6,7,8,9,10
     * 过滤奇数,只留下偶数
     * 并将结果保存起来
     * */
    public static void main(String[] args) {
        // 定义一个集合,并加入整数
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // 过滤奇数并保存
        List<Integer> newList = list.stream().filter(n -> n % 2 == 0).collect(Collectors.toList());

        System.out.println(newList);
    }
}

 Exercise 2 - String filtering and collecting

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 字符串过滤
 * @author: lh
 * @date: 2023年04月11日 20:16
 */
public class Demo2 {
    /*
     * 创建一个ArrayList集合,并添加以下字符串,字符串中前面是姓名,后面是年龄
     * "luMingFei,18"
     * "nuoNuo,16"
     * "chuZiHang,19"
     * 保留年龄大于等于18岁的人,并将结果收集到Map集合中,姓名为键,年龄为值
     * */
    public static void main(String[] args) {
        // 创建集合并添加数据
        List<String> list = new ArrayList<>();
        list.add("luMingFei,18");
        list.add("nuoNuo,16");
        list.add("chuZiHang,19");

        // 数据过滤收集
        Map<String, String> map = list.stream()
                .filter(s -> Integer.parseInt(s.split(",")[1]) >= 18)
                .collect(Collectors.toMap(s -> s.split(",")[0], s -> s.split(",")[1]));

        System.out.println(map);
    }
}

Guess you like

Origin blog.csdn.net/2301_76354366/article/details/130093322