简体   繁体   中英

Method containing interface as parameter

hello how do I call a method taking an interface as a parameter from the main ? The code in the main is an example of what I want to achieve but by calling the method map now

What do I write in my map method and how do I call it in the main ? Thank you

What I want to achieve :

StringTransformation addBlah = (e) -> {
    e += "boo";
     return e;
};
System.out.println(addBlah.transf("Hello")); // prints Helloboo

public class Main{

    public static void main(String[] args) {
        String a = hello;
        // How do I modify the string a by calling map ?


    }

    void map(StringTransformation t) {
        // What do I write ??
    }
}

public interface StringTransformation {
    String transf(String s);
}

You cannot call map inside the static main method. You must make map a static method as well if you want to do that. Also we can't help you with what to put inside your map function if you don't tell us what it should do.

public static void main(String[] args) {

    String string = "Hello";
    // you can call `mapBoo` like normal here
    string = mapBoo(string);
    System.out.println(string);

    List<String> strings = Arrays.asList("Hello", "this", "is", "a", "test");

    // or you can pass mapBoo into the stream.map method since map fits the method signature
    List<String> mappedStrings = strings.stream().map(Main::mapBoo)
            .collect(Collectors.toList());

    for (String mappedString : mappedStrings)
        System.out.println(mappedString);
}


static String mapBoo(String s) {
    return s + "boo";
}

You want to modify a String with a given StringTransformation so you need to pass both of them to the map method. Also you can turn addBlah in a more simple lambda :

public static void main(String[] args) {
    StringTransformation addBlah = (e) -> e + "boo";

    String str = "Hello";
    System.out.println(str);    // Hello
    str = map(addBlah, str);
    System.out.println(str);    // Helloboo
}

static String map(StringTransformation t, String argument) { 
    return t.transf(argument);     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM