Expression lambda Notes d'apprentissage du flux Strame :

  1. Format de base : (liste de paramètres) -> {bloc de code d'exécution}

  2. Trois éléments composent une expression Lambda : paramètres formels, flèches et blocs de code

  3. Conditions préalables à l'utilisation des expressions Lambda : 1) Il existe une interface ; 2) Il n'y a qu'une seule méthode abstraite dans l'interface

    Mode concis Lambda :

    • Le type de paramètre peut être omis, et un seul type de paramètre ne peut pas être omis dans le cas de plusieurs paramètres

    • Il n'y a qu'un seul paramètre, les parenthèses peuvent être omises

    • S'il n'y a qu'un seul bloc de code, les accolades et les points-virgules peuvent être omis. S'il y a retour, retour doit également être omis

    Considérations sur les expressions lambda :

    • Il y a une interface, et il n'y a qu'une seule méthode abstraite dans l'interface

    • L'utilisation de Lambda doit avoir un contexte afin d'en déduire l'interface correspondante de Lambda

    La différence entre Lambda et la classe interne anonyme :

    • Lambda ne peut s'engager que dans des interfaces

    • Lambda ne peut pas gérer le cas où il y a deux méthodes dans l'interface

    • Le principe d'implémentation est différent : après la compilation de la classe interne anonyme, un fichier de bytecode .class séparé sera généré.

public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程已经启动");
            }
        }).start();


        //使用lambda表达式书写

        new Thread(() -> {
            System.out.println("启动一个新的线程");
        }).start();
    }

Créer un flux

Collection à une seule colonne : collection object.stream()

	List<Author> author =new ArrayList<>();
				author.stream()

Tableaux : Arrays.stream(array) ou utilisez Stream.of() pour créer

Integer [] arr={1,2,3,4,5}
			Stream<Integer> stream = Arrarys.stream(arr);
			Stream<Integer> stream1=Stream.of(arr)
                

Collection à deux colonnes : créer après la conversion en une collection à une seule colonne

 HashMap<String, Integer> map = new HashMap<>();
        map.put("林聪",32);
        map.put("图图",32);
        map.put("郭大侠",23);
        Stream<Map.Entry<String, Integer>> stream = map.entrySet().stream();

Il existe 4 façons de parcourir la collection de cartes :

HashMap<String, Integer> map = new HashMap<>();
        map.put("林聪",32);
        map.put("图图",32);
        map.put("郭大侠",23);
		//方法1:通过获取key的set集合遍历key
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            System.out.println(s+map.get(s));

        }
		//方法2:通过拿到netrySet直接进行遍历
        for (Map.Entry<String, Integer> entry : map.entrySet()) {


        }
		//方法3:通过拿到entrySet使用Iterator进行遍历
        Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, Integer> next = iterator.next();

        }
		//方法4:通过map获取所有的值进行遍历

		Collection<Integer> values = map.values();
        for (Integer value : values) {
            
        }

Filtrer pour l'opération intermédiaire Stream


List<Author> authors = getAuthors();
        //打印所有作家名称大于2个字符的名称
        authors.stream().filter(author -> author.getName().length()>2).forEach(author -> System.out.println(author.getName()));


//原始方式:
List<Author> authors = getAuthors();
        //打印所有作家名称大于2个字符的名称
        authors.stream().filter(new Predicate<Author>() {
            @Override
            public boolean test(Author author) {
                
                return author.getName().length() > 2;
            }
        }).forEach(new Consumer<Author>() {
            @Override
            public void accept(Author author) {
                
                System.out.println(author.getName());
            }
        });
//使用熟练后可以直接装成lambda表达式

Carte de l'opération intermédiaire Stream

L'opération de carte peut calculer ou convertir le flux

 //只打印作者的姓名,lambda方式
authors.stream().map(Author::getName).forEach(System.out::println);

//匿名内部类方式:
        authors.stream().map(new Function<Author, String>() {

            @Override
            public String apply(Author author) {

                return author.getName();
            }
        }).forEach(System.out::println);

//对所有的年龄加10
  authors.stream().map(Author::getAge).map(age->age+10).forEach(System.out::println);

Fonctionnement intermédiaire distinct du flux

distinct peut supprimer les données de flux en double

Remarque : La méthode distinct s'appuie sur la méthode equals de Object pour déterminer s'il s'agit du même objet. Vous devez donc faire attention à réécrire la méthode equals.

Scorted (tri) de l'opération intermédiaire Stream

Si vous utilisez scorted avec des paramètres vides, vous devez réécrire l'interface de comparaison pour les objets du flux


//lambda方式
authors.stream().sorted((o1, o2) -> o1.getAge()-o2.getAge()).forEach(author -> System.out.println(author.getAge()));
//匿名内部类方式
 authors.stream().sorted(new Comparator<Author>() {
            @Override
            public int compare(Author o1, Author o2) {
               return o1.getAge()-o2.getAge();
             
            }
        }).forEach(author -> System.out.println(author.getAge()));

limite(n) de l'opérateur intermédiaire Stream

Définissez la longueur maximale du flux qui sera ignoré.

//截取前10个
authors.stream().limit(10).forEach(System.out::println);
 

Skip(n) of Stream intermédiaire opérateur

Ignorer les N premiers éléments du flux

//忽略流中第一个元素
authors.stream().skip(1).forEach(System.out::println);

flatMap de l'opérateur intermédiaire Stream

map ne peut convertir qu'un objet en un autre objet en tant qu'élément dans le flux, tandis que flatMap peut convertir un objet en plusieurs objets en tant qu'éléments dans le flux, obtenir la propriété d'un List<Book> dans l'objet et le convertir en un flux.

//匿名内部类实现
authors.stream().flatMap(new Function<Author, Stream<? extends Book>>() {
            @Override
            public Stream<? extends Book> apply(Author author) {
                
                return author.getBooks().stream();
            }
        }).forEach(book -> System.out.println(book.getName()));

//lambda方式实现
 authors.stream().flatMap(author -> author.getBooks().stream()).forEach(book -> System.out.println(book.getName()));


 //打印现有数据的全部分类,要求对分类进行去重
//使用lambda方式实现
        authors.stream().flatMap(author -> author.getBooks()
                .stream()).flatMap(book -> Arrays.stream(book.getCategory().split("、"))).distinct()
                .forEach(System.out::println);


//使用匿名内部类实现
 authors.stream().flatMap(new Function<Author, Stream<? extends Book>>() {
                    @Override
                    public Stream<? extends Book> apply(Author author) {
                        return author.getBooks()
                                .stream();
                    }
                }).flatMap(new Function<Book, Stream<? extends String>>() {
                    @Override
                    public Stream<? extends String> apply(Book book) {
                        return Arrays.stream(book.getCategory().split("、"));
                    }
                }).distinct()
                .forEach(System.out::println);


Opérateur de terminal de flux forEarch()

 //打印作者名称
 authors.forEach(author -> System.out.println(author.getName()));
//匿名类实现
authors.forEach(new Consumer<Author>() {
            @Override
            public void accept(Author author) {
                System.out.println(author.getName());
            }
        });

Opérateur de terminal de flux count()

Obtenir le nombre de flux


        long count = authors.stream().flatMap(author ->         author.getBooks().stream()).distinct().count();

        System.out.println(count);

## Opérateurs de terminaux de flux max() et min()

Tirez le meilleur parti du flux

   //获取最大值
   Optional<Integer> max = authors.stream().flatMap(author -> author.getBooks().stream()).map(Book::getScore)
                .max(Comparator.comparingInt(o -> o));
        System.out.println(max.get());

collect() de l'opérateur de terminal Stream

Convertir le flux actuel en collection

//获取所有存放作者名字的合集
List<String> list = authors.stream().map(Author::getName).collect(Collectors.toList());
        
        list.forEach(System.out::println);


//获取所有书名的set
Set<String> set = authors.stream().flatMap(author -> author.getBooks().stream()).map(Book::getName).collect(Collectors.toSet());
        set.forEach(System.out::println);

//获取键值为作者名,值为书名的map集合,使用匿名内部类实现
      Map<String, List<Book>> listMap = authors.stream().collect(Collectors.toMap(new Function<Author, String>() {
            @Override
            public String apply(Author author) {
                return author.getName();
            }
        }, new Function<Author, List<Book>>() {
            @Override
            public List<Book> apply(Author author) {
                return author.getBooks();
            }
        }));

        listMap.forEach((s, books) -> {System.out.println(s);
            books.forEach(book -> System.out.println(book.getName()));

        });


//使用lambda表达式实现

Map<String, List<Book>> listMap = authors.stream().collect(Collectors.toMap(Author::getName, Author::getBooks));
        listMap.forEach((s, books) -> {System.out.println(s);
            books.forEach(book -> System.out.println(book.getName()));

        });

Je suppose que tu aimes

Origine blog.csdn.net/qq_46063644/article/details/126570537
conseillé
Classement