Created
July 24, 2013 14:53
-
-
Save itallix/6071323 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class Main { | |
private static class Test { | |
Map<String, String> valuesMap = new HashMap<String, String>(); | |
public void process(String initialString) throws Exception { | |
if (!initialString.matches("^(;\\w+@\\w+)+;$")) { | |
throw new Exception("Incorrect line format regexp"); | |
} | |
String[] pairs = initialString.split(";"); | |
for (String pair : pairs) { | |
if (!pair.isEmpty()) { | |
String[] elements = pair.split("@"); | |
if (elements.length != 2) { | |
throw new Exception("Incorrect line format"); | |
} else { | |
valuesMap.put(elements[0], elements[1]); | |
} | |
} | |
} | |
} | |
public String getValue(String key) { | |
return valuesMap.get(key); | |
} | |
public String getKey(String value) { | |
for (String key : valuesMap.keySet()) { | |
if (valuesMap.get(key).equals(value)) { | |
return key; | |
} | |
} | |
return null; | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
Test test = new Test(); | |
test.process(";key1@value2;key2@value;key2@value2;"); | |
System.out.println("Key for value2: " + test.getKey("value2")); | |
System.out.println("Value for key2: " + test.getValue("key2")); | |
System.out.println("Value for null: " + test.getValue(null)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment