• 迭代器适配器方法惯用法


    package t20211225;
    
    import java.util.*;
    
    /**
     * @Author: DengJia
     * @Date: 2021/12/26 10:04
     * @Description: 顺序迭代、逆序迭代、乱序迭代
     */
    
    public class IterableClass implements Iterable<String> {
        protected String[] words = ("1 2 3 4 5 6 7 8 9 0").split(" ");
    
        @Override
        public Iterator<String> iterator() {
            return new Iterator<String>() {
                private int index = 0;
    
                @Override
                public boolean hasNext() {
                    return index < words.length;
                }
    
                @Override
                public String next() {
                    return words[index++];
                }
    
                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    
        public static void main(String[] args) {
            MultiIterableClass mic = new MultiIterableClass();
            System.out.print("顺序迭代:");
            for (String s : mic) {
                System.out.print(s + " ");
            }
            System.out.print("\n逆序迭代:");
            for (String s : mic.reversed()) {
                System.out.print(s + " ");
            }
            System.out.print("\n乱序迭代:");
            for (String s : mic.randomized()) {
                System.out.print(s + " ");
            }
        }
    }
    
    class MultiIterableClass extends IterableClass {
        public Iterable<String> reversed() {
            return () -> new Iterator<String>() {
                int current = words.length - 1;
    
                @Override
                public boolean hasNext() {
                    return current > -1;
                }
    
                @Override
                public String next() {
                    return words[current--];
                }
    
                @Override
                public void remove() {
                    throw new UnsupportedOperationException();
                }
            };
        }
    
        public Iterable<String> randomized() {
            return () -> {
                // 洗牌
                List<String> shuffled = new ArrayList<>(Arrays.asList(words));
                Collections.shuffle(shuffled, new Random(47));
                return shuffled.iterator();
            };
        }
    }
    
    
    顺序迭代:1 2 3 4 5 6 7 8 9 0 
    逆序迭代:0 9 8 7 6 5 4 3 2 1 
    乱序迭代:4 6 3 1 8 7 2 5 0 9 
    
    DJOSIMON
  • 相关阅读:
    EKLM3S8962之LED
    [uClinuxdev] detecting stack overflow
    Eclipse换行符
    EKLM3S8962之OLED
    Windows 环境下 GNU ARM 开发环境建立
    关于阻焊层和助焊层的理解
    MISRA C 2004中文版
    对话框托盘程序实现源码
    VC++中四种进程或线程同步互斥的控制方法
    Windows线程同步与互斥技术总结
  • 原文地址:https://www.cnblogs.com/DJOSIMON/p/15732758.html
Copyright © 2020-2023  润新知