Start New Discussion within our Software Development Community

Hi, I wrote a method that accepted a parameter and used a hashmap to return the value for that key. However I have been asked to change the way it is written so that code isn't duplicated. The hashmap used has key value pairs such as 'X', 'Y' in one method and in the second it is 'Y', 'X'. But now they want just one method that will take in either X or Y, loop through the hashmap using the entry set I think and return either X or Y. I've been shown to declare the hashmap at the top of the class.

 private static final Map<String, String> Values = new HashMap<String, String>();

    Values.put("X", "Y");

The code I was given to help me start was

String lookupVal = null;
        boolean T = true;
        for(Entry<String, String> entry :Value.entrySet()){
        LookUp = T ? entry.getValue(): entry.getKey();

I wasn't given much information on what this does and I haven't used Java in a very long time so I was really just wanting someone to explain what I need to do to get either the key or value returned based on the parameter that is passed. This could be very easy but I just can't get it and Java seems to have changed since I last used it especially the ternary operator, can't seem to get my head round it fully.

Any help would be great

I tried reading that a few times, but it still makes no sense, and the code you were given (a) also makes no sense and (b) isn't valid code and (c) goes out of its way to break Java naming conventions just to confuse us all.

Since both key and value are Strings, there's no way to determine which is being looked for when all you have is a String parameter.

What I can help with is the ternary operator, which was present from the very first drafts of the Java language (and many other languages). It goes like this

<variable> = <boolean expression> ?  <expression 1> : <expression 2>;

which is equivalent to

if ( <boolean expression> ) {
   <variable> =  <expression 1>;
} else {
   <variable> =  <expression 2>;
This article has been dead for over six months. Start a new discussion instead.