Search code examples
javastringsigned

How can I distinguish a String(of characters) leading a minus sign in JAVA? ex: "buy" and "-buy"


I am comparatively new in JAVA. I am implementing an idea involving multimap. Now I want to put "buy" and "-buy" as the key. My question is, how can I distinguish that the original string(characters) is same but they have opposing leading sign???


Solution

  • I think you might be misusing the concept of multimaps. I am gathering from your question that you want to look up a single key and have it return values for two keys (with and without '-' before them). Multimaps don't support multiple keys (as far as I'm aware in any case). They support multiple values for each key.

    You have a number of options:

    1. Don't encode the 'opposite' semantic in the key. Rather create a new class with the String and a boolean field for flagging opposite and use that class as your key.

      public class Operation { String getName(); Boolean isOpposite(); }

      Map> map;

    2. Don't include the logic on opposites in the data structure at all. Rather parse the key on usage. In other words you would need to get both "buy" and "-buy" as keys and then sort out what to do with each in your code.

    3. Make your Map two levels with the second level representing whether the values are opposite or not:

      Map<String,Map<Boolean,List<Value>>> map;

      map.get("buy").get(true)...

    The first option is definitely the best in my view. The text associated with the values should just be one attribute of your key - if you end up having to add others then you will end up with a bunch of logic encoded in the key.