Java中的forEach没有下标?那就自己实现

public static <T> Consumer<T> getIndex(BiConsumer<T, Integer> consumer) {
        class IndexObject {
            int index;
        }
        IndexObject indexObject = new IndexObject();
        return i -> {
            consumer.accept(i, indexObject.index++);
        };
    }

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("花果山", "水帘洞", "盘丝洞");
        // 用法
        strings.forEach(getIndex((item, index) -> {
            System.out.println(item + "下标为:" + index);
        }));
    }

输出结果:

花果山下标为:0
水帘洞下标为:1
盘丝洞下标为:2 

=========================================================================

给大家推荐一个超实用的方法 -- String.join();可以使用它进行元素的拼接,如下:  

public static void main(String[] args) {
        // 集合的用法
        List<String> strings = Arrays.asList("花果山", "水帘洞", "盘丝洞");
        String join = String.join(",", strings);
        System.out.println("集合拼接结果 = " + join);
        // 数组的用法
        String[] s = {"花果山", "水帘洞", "盘丝洞"};
        String joins = String.join(",", s);
        System.out.println("数组拼接结果 = " + joins);
    }

输出结果:

集合拼接结果 = 花果山,水帘洞,盘丝洞
数组拼接结果 = 花果山,水帘洞,盘丝洞 

猜你喜欢

转载自blog.csdn.net/qq_38238956/article/details/124928104