Last active
April 5, 2021 18:44
-
-
Save Yuhtin/ef765a8155d8aa349e6f75ec6ace7b04 to your computer and use it in GitHub Desktop.
Case insensitive string as HashMap key
This file contains 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
/** | |
* @author Yuhtin | |
* Github: https://github.com/Yuhtin | |
*/ | |
public class CaseInsensitiveExample { | |
static final CaseInsensitiveLinkedMap<Character> CHARACTER_MAP = CaseInsensitiveLinkedMap.newMap(); | |
public static void main(String[] args) { | |
// populate map | |
CHARACTER_MAP.put("LetterA", 'a'); | |
// get value from map | |
Character character = CHARACTER_MAP.get("lEttErA"); | |
System.out.println(character.toString()); // Prints: a | |
} | |
} |
This file contains 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.LinkedHashMap; | |
/** | |
* @author Yuhtin | |
* Github: https://github.com/Yuhtin | |
*/ | |
public class CaseInsensitiveLinkedMap<V> extends LinkedHashMap<String, V> { | |
public static <V> CaseInsensitiveLinkedMap<V> newMap() { | |
return new CaseInsensitiveLinkedMap<>(); | |
} | |
@Override | |
public V get(Object key) { | |
String keyFounded = this.keySet() | |
.stream() | |
.filter(keyMap -> keyMap.equalsIgnoreCase((String) key)) | |
.findAny() | |
.orElse(null); | |
return keyFounded == null ? null : super.get(keyFounded); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment