Monday, September 19, 2022

[FIXED] how to pass a String value to the following function

Issue

I have the following function with a consumer

Collection<String> abc;
@Override
public void something(Consumer<? super String> visitor) {

 abc.add(visitor);
}

I want to add values received to something function in the abc list. but I don't know how that will work?

In Main, I have the following code

String value = "usman"
   something(what should I write here to pass value and use in something)

Solution

If your method something has argument Consumer<? super String> visitor, it means that you pass a function to the method something which accepts a String argument and returns nothing.

That is, you should be passing a function defined as a lambda expression: s -> abc.add(s)

Such function consumes String value (yet to be provided) and adds it to some collection.

Thus, you should have a code like this:

import java.util.*;
import java.util.function.*;


public class MyClass {
    
    static Collection<String> abc = new ArrayList<>();
    
    static void something(Consumer<? super String> visitor) {
        String value = "usman"; 
        visitor.accept(value);
    }

    public static void main(String [] args) {
        
        something(s -> abc.add(s));
        
        System.out.println(abc);
    }
}

The output printed shows that the local value defined within something has been added to the collection:

[usman]

Update

If you need to use the value passed outside something method, you can just ignore the value passed to the Consumer:

public static void main(String[] args) {
    String mainValue = "mainValue";
    Supplier<String> supplier = () -> "supplier";

    something(s -> abc.add("literal"));
    something(s -> abc.add(mainValue));
    something(s -> abc.add(supplier.get()));

    System.out.println(abc);
}

Then only outer values are added to the collection:

[literal, mainValue, supplier]


Answered By - Nowhere Man
Answer Checked By - Robin (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.