Skip to content

Instantly share code, notes, and snippets.

@Yuhtin
Last active April 5, 2021 18:44
Show Gist options
  • Save Yuhtin/ef765a8155d8aa349e6f75ec6ace7b04 to your computer and use it in GitHub Desktop.
Save Yuhtin/ef765a8155d8aa349e6f75ec6ace7b04 to your computer and use it in GitHub Desktop.
Case insensitive string as HashMap key
/**
* @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
}
}
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