java stream map

return transfer
<R> Stream<R> map(Function<? super T,? extends R> mapper)

The parameter is an Interface Function<T,R>object, (the return type of Functionthe apply(T t)method that needs to manually implement the interface is R)
? super Tis the type of the input, and
? extends Rthe return type is clearR

1. The internal class implementation method, writing one: anonymous internal class The generic type
here Functionhas <T,R>become an <String,String>
overridden applymethod, the parameter type has Tbecome String, and the return value type Rhas also becomeString

    public static void main(String[] args) throws IOException {
    
    
        List<String> list1 = Arrays.asList("1","2","3");
        list1.stream().map(
                new Function<String, String>() {
    
    
                    @Override
                    public String apply(String s) {
    
    
                        s += s;
                        return s;
                    }
                }
        ).forEach(System.out::println);
    }

2. The internal class implementation method, the second way of writing: the internal class

    public static void main(String[] args) throws IOException {
    
    
        List<String> list1 = Arrays.asList("1","2","3");
        list1.stream().map(
            new Fun()
        ).forEach(System.out::println);
    }
//实现接口时,泛型是写在接口上
    static class Fun implements Function<String,String>{
    
    //为什么要加static
        @Override
        public String apply(String s) {
    
    
            s += s;
            return s;
        }
    }

3.
lambdaThe essence of using lambda is the Functioninner class

    public static void main(String[] args) throws IOException {
    
    
        List<String> list1 = Arrays.asList("1","2","3");
        list1.stream().map(
            x -> x+=x
        ).forEach(System.out::println);
    }

Guess you like

Origin blog.csdn.net/claroja/article/details/113899980