Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the return String from a method stored in Hashmap?

I have the following method:

 public String randomValueGenerator(String item, int id){
        RandomGenerator randomGenerator = new RandomGenerator();
        HashMap<Integer, Runnable> map = new HashMap<Integer, Runnable>();
        map.put(1, () -> randomGenerator.generateFirstName());
        map.put(2, () -> randomGenerator.generateLastName());

        if (item==""){

            String rdn = map.get(id).run();
            return rdn;
        }else {
            return item;
        }
    }

I checking that the item is an empty string and if it is I would like to generate a random value and return it. (If not empty return as it was.)

I have problem with store the return String from the generateFirstName / generateLastName.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try

public String randomValueGenerator(String item, int id){
        RandomGenerator randomGenerator = new RandomGenerator();
        // Use supplier instead of runnable
        HashMap<Integer, Supplier<String>> map = new HashMap<>(); 
        map.put(1, () -> randomGenerator.generateFirstName());
        map.put(2, () -> randomGenerator.generateLastName());

        if (item==""){

            String rdn = map.get(id).get(); //<-- get instead of run
            return rdn;
        }else {
            return item;
        }
    }

The ()-> is a lambda-notation. Runnable will return void, Supplier<String> will return String.

One more thing: You are comparing item=="" this might not always work, you better use item.intern()=="" or "".equals(item).

Edit: Please honor EdsonPassos comment item.isEmpty() is better than item.intern()=="".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading