Map<String,String> votes = new HashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
How can I retrieve the value that most a occur in the HashMap above, in this case that would be "School". I would appreciate the most efficient and clear method to approach.
A simpler solution is to just look at the values.
public static <E> E mostFrequentElement(Iterable<E> iterable) {
Map<E, Integer> freqMap = new HashMap<>();
E mostFreq = null;
int mostFreqCount = -1;
for (E e : iterable) {
Integer count = freqMap.get(e);
freqMap.put(e, count = (count == null ? 1 : count+1));
// maintain the most frequent in a single pass.
if (count > mostFreqCount) {
mostFreq = e;
mostFreqCount = count;
}
}
return mostFreq;
}
and for a Map you can do
V v = mostFrequentElement(map.values());
One solution would be:
Construct a new HashMap that has a String key and an int value.
For each value of your current HashMap:
Add the value as the key in the new HashMap and the value as 1 if it's the first time you're inserting it.
Otherwise, increment the value by one for the current key.
Now iterate on the newly created map and retrieve the key that has the maximum value.
For your current map:
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
You'll first insert School as a key, with value 1. Then you face School again, so you increment the value by 1, having a count of 2. Now you insert Work with value 1, and Party with value 1 as well.
After iterating on the map, you'll get School with the highest value. And that's what you want!
Just using the API :
Map<String,String> votes = new HashMap<String,String>();
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
Collection<String> c = votes.values();
List<String> l = new ArrayList<>(c);
Set<String> set = new HashSet<>(c);
Iterator<String> i = set.iterator();
String valueMax = "";
int max = 0;
while(i.hasNext()){
String s = i.next();
int frequence = Collections.frequency(l, s);
if(frequence > max){
max = frequence;
valueMax = s;
}
}
System.out.println(valueMax+": "+max);
Output :
School: 2
Here is the implementation of Maroun pseudocode. Try,
Map<String, String> votes = new HashMap<String, String>();
votes.put("Henk", "School");
votes.put("Elise", "School");
votes.put("Jan", "Work");
votes.put("Mert", "Party");
//Define a countMap with String as value, Integer for count
Map<String, Integer> countMap = new HashMap<>();
for (Map.Entry<String, String> entry : votes.entrySet()) {
if (countMap.containsKey(entry.getValue())) {
countMap.put(entry.getValue(), countMap.get(entry.getValue()) + 1);
} else {
countMap.put(entry.getValue(), 1);
}
}
// Got the number of maximum occuarance
Integer maxNum = Collections.max(countMap.values());
String result = "";
// Iterate to search the result.
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
if(maxNum==entry.getValue()){
result=entry.getKey();
}
}
System.out.println(result);
I believe this will do what you want -
/**
* Get the most frequent value present in a map.
*
* #param map
* The map to search.
* #return The most frequent value in the map (or null).
*/
public static <K, V> V getMostFrequentValue(
Map<K, V> map) {
// Make sure we have an entry.
if (map != null && map.size() > 0) {
// the entryset from our input.
Set<Entry<K, V>> entries = map.entrySet();
// we need a map to hold the count.
Map<V, Integer> countMap = new HashMap<V, Integer>();
// iterate the entries.
for (Entry<K, V> entry : entries) {
// get the value.
V value = entry.getValue();
if (countMap.containsKey(value)) {
// if we've seen it before increment the previous
// value.
countMap.put(value, countMap.get(value) + 1);
} else {
// otherwise, store 1.
countMap.put(value, 1);
}
}
// A holder for the maximum.
V maxV = null;
for (Entry<V, Integer> count : countMap.entrySet()) {
if (maxV == null) {
maxV = count.getKey();
continue;
}
if (count.getValue() > countMap.get(maxV)) {
maxV = count.getKey();
}
}
return maxV;
}
return null;
}
You could override the put() and remove() of the HashMap class and create your custom one that also controls for the number of objects added. Like so:
public class MyHashMap<K, V> extends HashMap<K, V> {
private HashMap<String, Integer> countMap = new HashMap<String, Integer>();
#Override
public V put(K key, V value) {
Integer count = countMap.get(value);
if (count != null) {
countMap.put((String) value, ++count);
} else {
countMap.put((String) value, new Integer(1));
}
return super.put(key, value);
}
#Override
public V remove(Object key) {
String countKey = (String) get(key);
Integer count = countMap.get(countKey);
if (count != null) {
countMap.put(countKey, --count);
}
return super.remove(key);
}
public Integer getCount(Object value) {
return countMap.get((String)value);
}
}
This way you don't have to loop over the elements of your HashMap to count them. Instead, after you add them:
Map<String,String> votes = new MyHashMap<String,String>
votes.put("Henk","School");
votes.put("Elise","School");
votes.put("Jan","Work");
votes.put("Mert","Party");
You could just get the count for each as:
Integer schoolCount = votes.getCount("School");
Related
I have a tree map declared as follows:
TreeMap<Integer, Integer> tree = new TreeMap<Integer, Integer>();
How do I retrieve the key with the maximum value. Is there an O(1) way of achieving this. I know that maximum and minimum keys can be retrieved from a TreeMap in O(1) time as follows:
int maxKey = tree.lastEntry().getKey();
int minKey = tree.firstEntry().getKey();
Thanks for help.
The collection is not sorted by value so the only way is brute force O(n) unless there is another collection with say the reverse map available.
Map<Integer, Integer>map = new TreeMap<>();
int max = map.values().stream().max(Integer::compare).get();
O(1) complexity is not possible with TreeMap. you need to create one more map which uses value of first map as keys. or use BiMap
public TreeBiMap implements Map {
private Map<Integer, Integer> map;
private Map<Integer, Integer> reverseMap;
public TreeBiMap() {
map = new TreeMap<>();
reverseMap = new TreeMap<>();
}
public void put(Integer key, Integer value) {
map.put(key, value);
reverseMap.put(value, key);
}
public Integer getMaxValue() {
return reverseMap.lastEntry().getKey()
}
}
The answer provided by #PeterLawrey answers the question fair enough. If you are looking for a simpler implementation, here it is:
TreeMap<Integer, Integer> tree = new TreeMap<Integer, Integer>();
// populate the tree with values
Map.Entry<Integer, Integer> maxEntry = null;
for(Map.Entry<Integer, Integer> entry : tree.entrySet()){
if(maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
maxEntry = entry;
}
System.out.println("The key with maximum value is : " + maxEntry.getKey());
Do you depend on using a TreeMap/do you fill it yourself? I ran into a similar situation and extended the TreeMap by the missing functionality:
public class TreeMapInteger<T> extends TreeMap<Integer,T> {
private static final long serialVersionUID = -1193822925120665963L;
private int minKey = Integer.MAX_VALUE;
private int maxKey = Integer.MIN_VALUE;
#Override
public T put(Integer key, T value) {
if(key > maxKey) {
maxKey = key;
}
if(key < minKey) {
minKey = key;
}
return super.put(key, value);
}
public int getMaxKey() {
return maxKey;
}
public int getMinKey() {
return minKey;
}
}
This won't decrease the complexity but depending on when and how your Map is filled having the values prepared for you when you need them might be preferable.
As others have said, you basically have to iterator each map entry and find the entry with the largest value.
Note that in your post you made a mistake.
I know that maximum and minimum keys can be retrieved from a TreeMap
in O(1) time as follows:
int maxKey = tree.lastEntry().getKey();
int minKey = tree.firstEntry().getKey();
I think the time complexity should be O(lgn).
The source code of getLastEntry:
/**
* Returns the last Entry in the TreeMap (according to the TreeMap's
* key-sort function). Returns null if the TreeMap is empty.
*/
final Entry<K,V> getLastEntry() {
Entry<K,V> p = root;
if (p != null)
while (p.right != null)
p = p.right;
return p;
}
Also refer to this post in SO
Using Java 1.5 how can I convert the following list structure to a nested map:
List<CsSectionDetail> list to Map<Integer,Map<Integer, List<CsSectionDetail>>> map = new TreeMap<Integer, Map<Integer,List<CsSectionDetail>>>();
The above list contains two keys mainTaskId and subTaskId which should be converted to the above map structure with first Integer mainTaskId and second Integer subTaskId.
I already have a function to convert List<CsSectionDetail> list to map , with the structure Map<Integer, List<CsSectionDetail>> map = new HashMap<Integer, List<CsSectionDetail>>();
Below is the code
public Map<Integer, List<CsSectionDetail>> getCsSectionDetail4Display(List<CsSectionDetail> list, boolean groupByMainTaskOnly) {
Map<Integer, List<CsSectionDetail>> map = new HashMap<Integer, List<CsSectionDetail>>();
Iterator<CsSectionDetail> it = list.iterator();
while(it.hasNext()){
CsSectionDetail csDetail = (CsSectionDetail) it.next();
add2Map(csDetail, map, groupByMainTaskOnly);
}
return map;
}
private void add2Map(CsSectionDetail csDetail, Map<Integer, List<CsSectionDetail>> map, boolean groupByMainTaskOnly) {
List<CsSectionDetail> list;
Integer key;
if (groupByMainTaskOnly) {
key = csDetail.getProjectTaskId().getId();
} else {
if (csDetail.getProjectSubTaskId() == 0) {
key = csDetail.getProjectTaskId().getId();
} else {
key = new Integer(csDetail.getProjectSubTaskId());
}
}
list = (List<CsSectionDetail>) map.get(key);
if (list == null) {
list = new ArrayList<CsSectionDetail>();
}
How can modify the above code to get the nested map structure?
Thanks
Cut your code in two methods for clarity, each filling the map at a different level:
private void add2TaskMap(CsSectionDetail csDetail, Map<Integer, Map<Integer,CsSectionDetail>> map) {
Map<Integer,CsSectionDetail> submap;
Integer key = csDetail.getProjectTaskId().getId();
submap =map.get(key);
if (submap == null) {
submap = new HashMap<Integer,CsSectionDetail>();
map.put(key, submap);
}
add2SubTaskMap(csDetail, submap);
}
private void add2SubTaskMap(CsSectionDetail csDetail, Map<Integer,CsSectionDetail> map) {
Integer key;
if (csDetail.getProjectSubTaskId() == 0) {
key = csDetail.getProjectTaskId().getId();
} else {
key = new Integer(csDetail.getProjectSubTaskId());
}
map.put(key, csDetail);
}
I need to reverse the order of what the below method returns. For example if it
returns:
1=ball, 2=save, 3=take 4=till
I want to reverse and return:
1=till, 2=take, 3=save, 4=ball
My method is:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map;
}
Please check if the below code I've written is useful for you as a reference:
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> iterator = keySet.descendingIterator();
Integer i;
while(iterator.hasNext())
{
i = iterator.next();
reverseMap.put(i,map.get(i));
}
System.out.println(reverseMap);
}
//map to arrange inizialized
LinkedHashMap<String,object> mta;
//transforms into arrayList hashmap keys and values
ArrayList<Object> valuesTMP=new ArrayList<Object>(mta.values());
ArrayList<String> keysTMP;
keysTMP=new ArrayList<String>(mta.keySet());
//reverse
Collections.reverse(valuesTMP);
Collections.reverse(keysTMP);
LinkedHashMap <String,Object> mtarranged=new LinkedHashMap<String, Object>();
int index=0;
for( String key : keysTMP){
mtarranged.put(key,valuesTMP.get(index));
index++;
}
To answer this question, we need to know how you're iterating the Map since Maps don't have entry order. However, you may try using a TreeMap which has the method descendingMap:
public Map<Integer, String> returnMapOfValues(ArrayList<String> wordsList) {
TreeMap<Integer, String> map = new TreeMap<Integer, String>();
int getFrequencyValue = 0;
Set<String> uniqueSetWords = new HashSet<String>(wordsList);
for (String temp : uniqueSetWords) {
getFrequencyValue = Collections.frequency(wordsList, temp);
//prints the Collection of words and they frequency, For testing only
//System.out.println(temp + ":" + Collections.frequency(wordsList,
//temp));
map.put(getFrequencyValue, temp);
getFrequencyValue = 0;
}
return map.descendingMap();
}
Edit: From your comment, your intent is more clear. A TreeMap will help you with your goal because it is a Map ordered by the natural order of the keys.
I've made some changes to the code. Please check if this is OK for you now.
public void reverseMap()
{
NavigableMap<Integer,String> map = new TreeMap<Integer,String>();
LinkedHashMap<Integer,String> reverseMap = new LinkedHashMap<Integer,String>();
map.put(1,"Apple");
map.put(2,"Ball");
map.put(3,"Cat");
NavigableSet<Integer> keySet = map.navigableKeySet();
Iterator<Integer> forwardIterator = keySet.iterator();
Iterator<Integer> reverseIterator = keySet.descendingIterator();
Integer i;
Integer j;
while(forwardIterator.hasNext())
{
i = forwardIterator.next();
j = reverseIterator.next();
reverseMap.put(i,map.get(j));
}
System.out.println(reverseMap);
}
Please find the below code and Let me know Which is suitable for you ...
int iterationValue = 0;
List<String> stringList = new LinkedList<String>();
stringList.add("ball");
stringList.add("save");
stringList.add("tick");
Map<Integer, String> map = new HashMap<Integer, String>();
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Input MAP
System.out.println(map); // {0=ball, 1=save, 2=tick}
Collections.reverse(stringList);
iterationValue = 0;
for (String temp : stringList) {
map.put(iterationValue++, temp);
}
// Output MAP
System.out.println(map); // {0=tick, 1=save, 2=ball}
I'm trying to get results HashMap sorted by value.
This is HashMap's keys and values:
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
I try to get results like this:
1 = can
2 = selin
4 = burak
5 = ertu
Here is my code:
import java.util.*;
public class mapTers {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext()) {
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++) {
while (t.hasNext()) {
if (dizi[i].equals(map.get(t.next()))) {
System.out.println(dizi[i] + " = " + t.next());
}
}
}
}
}
You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.
Here's my solution:
import java.util.*;
public class mapTers
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext())
{
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++)
{
t = anahtarlar.iterator();
while (t.hasNext())
{
String temp = (String)t.next();
if (dizi[i].equals(map.get(temp)))
{
System.out.println(dizi[i] + " = " + temp);
}
}
}
}
}
You cannot do that from a Map. At least not directly.
Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.
Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.
This is one of the solutions take from: https://stackoverflow.com/a/13913206/1256583
Just pass in the unsorted map, and you'll get the sorted one.
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
}
else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
To print, do a simple iteration over the entry set:
public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
You probably have the wrong data structure for this problem. Either:
Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
Use a bidirectional map as provided by libraries like Google Guava.
Reversed Map
private final SortedMap<Integer, String> TRANSLATIONS;
static {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "can");
// ...
TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}
Guava BiMap
private final BiMap TRANSLATIONS =
new ImmutableBiMap.Builder<String, Integer>()
.put("ertu", 5);
.put("burak", 4);
.put("selin", 2);
.put("can", 1);
.build();
Then, iterate over a sorted version of the key set or value set as needed. For example,
TRANSLATIONS.inverse.get(4); // "burak"
I'm just curious. What language are your strings in?
Consider you have a map<String, Object> myMap.
Given the expression "some.string.*", I have to retrieve all the values from myMap whose keys starts with this expression.
I am trying to avoid for loops because myMap will be given a set of expressions not only one and using for loop for each expression becomes cumbersome performance wise.
What is the fastest way to do this?
If you work with NavigableMap (e.g. TreeMap), you can use benefits of underlying tree data structure, and do something like this (with O(lg(N)) complexity):
public SortedMap<String, Object> getByPrefix(
NavigableMap<String, Object> myMap,
String prefix ) {
return myMap.subMap( prefix, prefix + Character.MAX_VALUE );
}
More expanded example:
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
public class Test {
public static void main( String[] args ) {
TreeMap<String, Object> myMap = new TreeMap<String, Object>();
myMap.put( "111-hello", null );
myMap.put( "111-world", null );
myMap.put( "111-test", null );
myMap.put( "111-java", null );
myMap.put( "123-one", null );
myMap.put( "123-two", null );
myMap.put( "123--three", null );
myMap.put( "123--four", null );
myMap.put( "125-hello", null );
myMap.put( "125--world", null );
System.out.println( "111 \t" + getByPrefix( myMap, "111" ) );
System.out.println( "123 \t" + getByPrefix( myMap, "123" ) );
System.out.println( "123-- \t" + getByPrefix( myMap, "123--" ) );
System.out.println( "12 \t" + getByPrefix( myMap, "12" ) );
}
private static SortedMap<String, Object> getByPrefix(
NavigableMap<String, Object> myMap,
String prefix ) {
return myMap.subMap( prefix, prefix + Character.MAX_VALUE );
}
}
Output is:
111 {111-hello=null, 111-java=null, 111-test=null, 111-world=null}
123 {123--four=null, 123--three=null, 123-one=null, 123-two=null}
123-- {123--four=null, 123--three=null}
12 {123--four=null, 123--three=null, 123-one=null, 123-two=null, 125--world=null, 125-hello=null}
I wrote a MapFilter recently for just such a need. You can also filter filtered maps which makes then really useful.
If your expressions have common roots like "some.byte" and "some.string" then filtering by the common root first ("some." in this case) will save you a great deal of time. See main for some trivial examples.
Note that making changes to the filtered map changes the underlying map.
public class MapFilter<T> implements Map<String, T> {
// The enclosed map -- could also be a MapFilter.
final private Map<String, T> map;
// Use a TreeMap for predictable iteration order.
// Store Map.Entry to reflect changes down into the underlying map.
// The Key is the shortened string. The entry.key is the full string.
final private Map<String, Map.Entry<String, T>> entries = new TreeMap<>();
// The prefix they are looking for in this map.
final private String prefix;
public MapFilter(Map<String, T> map, String prefix) {
// Store my backing map.
this.map = map;
// Record my prefix.
this.prefix = prefix;
// Build my entries.
rebuildEntries();
}
public MapFilter(Map<String, T> map) {
this(map, "");
}
private synchronized void rebuildEntries() {
// Start empty.
entries.clear();
// Build my entry set.
for (Map.Entry<String, T> e : map.entrySet()) {
String key = e.getKey();
// Retain each one that starts with the specified prefix.
if (key.startsWith(prefix)) {
// Key it on the remainder.
String k = key.substring(prefix.length());
// Entries k always contains the LAST occurrence if there are multiples.
entries.put(k, e);
}
}
}
#Override
public String toString() {
return "MapFilter(" + prefix + ") of " + map + " containing " + entrySet();
}
// Constructor from a properties file.
public MapFilter(Properties p, String prefix) {
// Properties extends HashTable<Object,Object> so it implements Map.
// I need Map<String,T> so I wrap it in a HashMap for simplicity.
// Java-8 breaks if we use diamond inference.
this(new HashMap<>((Map) p), prefix);
}
// Helper to fast filter the map.
public MapFilter<T> filter(String prefix) {
// Wrap me in a new filter.
return new MapFilter<>(this, prefix);
}
// Count my entries.
#Override
public int size() {
return entries.size();
}
// Are we empty.
#Override
public boolean isEmpty() {
return entries.isEmpty();
}
// Is this key in me?
#Override
public boolean containsKey(Object key) {
return entries.containsKey(key);
}
// Is this value in me.
#Override
public boolean containsValue(Object value) {
// Walk the values.
for (Map.Entry<String, T> e : entries.values()) {
if (value.equals(e.getValue())) {
// Its there!
return true;
}
}
return false;
}
// Get the referenced value - if present.
#Override
public T get(Object key) {
return get(key, null);
}
// Get the referenced value - if present.
public T get(Object key, T dflt) {
Map.Entry<String, T> e = entries.get((String) key);
return e != null ? e.getValue() : dflt;
}
// Add to the underlying map.
#Override
public T put(String key, T value) {
T old = null;
// Do I have an entry for it already?
Map.Entry<String, T> entry = entries.get(key);
// Was it already there?
if (entry != null) {
// Yes. Just update it.
old = entry.setValue(value);
} else {
// Add it to the map.
map.put(prefix + key, value);
// Rebuild.
rebuildEntries();
}
return old;
}
// Get rid of that one.
#Override
public T remove(Object key) {
// Do I have an entry for it?
Map.Entry<String, T> entry = entries.get((String) key);
if (entry != null) {
entries.remove(key);
// Change the underlying map.
return map.remove(prefix + key);
}
return null;
}
// Add all of them.
#Override
public void putAll(Map<? extends String, ? extends T> m) {
for (Map.Entry<? extends String, ? extends T> e : m.entrySet()) {
put(e.getKey(), e.getValue());
}
}
// Clear everything out.
#Override
public void clear() {
// Just remove mine.
// This does not clear the underlying map - perhaps it should remove the filtered entries.
for (String key : entries.keySet()) {
map.remove(prefix + key);
}
entries.clear();
}
#Override
public Set<String> keySet() {
return entries.keySet();
}
#Override
public Collection<T> values() {
// Roll them all out into a new ArrayList.
List<T> values = new ArrayList<>();
for (Map.Entry<String, T> v : entries.values()) {
values.add(v.getValue());
}
return values;
}
#Override
public Set<Map.Entry<String, T>> entrySet() {
// Roll them all out into a new TreeSet.
Set<Map.Entry<String, T>> entrySet = new TreeSet<>();
for (Map.Entry<String, Map.Entry<String, T>> v : entries.entrySet()) {
entrySet.add(new Entry<>(v));
}
return entrySet;
}
/**
* An entry.
*
* #param <T> The type of the value.
*/
private static class Entry<T> implements Map.Entry<String, T>, Comparable<Entry<T>> {
// Note that entry in the entry is an entry in the underlying map.
private final Map.Entry<String, Map.Entry<String, T>> entry;
Entry(Map.Entry<String, Map.Entry<String, T>> entry) {
this.entry = entry;
}
#Override
public String getKey() {
return entry.getKey();
}
#Override
public T getValue() {
// Remember that the value is the entry in the underlying map.
return entry.getValue().getValue();
}
#Override
public T setValue(T newValue) {
// Remember that the value is the entry in the underlying map.
return entry.getValue().setValue(newValue);
}
#Override
public boolean equals(Object o) {
if (!(o instanceof Entry)) {
return false;
}
Entry e = (Entry) o;
return getKey().equals(e.getKey()) && getValue().equals(e.getValue());
}
#Override
public int hashCode() {
return getKey().hashCode() ^ getValue().hashCode();
}
#Override
public String toString() {
return getKey() + "=" + getValue();
}
#Override
public int compareTo(Entry<T> o) {
return getKey().compareTo(o.getKey());
}
}
// Simple tests.
public static void main(String[] args) {
String[] samples = {
"Some.For.Me",
"Some.For.You",
"Some.More",
"Yet.More"};
Map map = new HashMap();
for (String s : samples) {
map.put(s, s);
}
Map all = new MapFilter(map);
Map some = new MapFilter(map, "Some.");
Map someFor = new MapFilter(some, "For.");
System.out.println("All: " + all);
System.out.println("Some: " + some);
System.out.println("Some.For: " + someFor);
Properties props = new Properties();
props.setProperty("namespace.prop1", "value1");
props.setProperty("namespace.prop2", "value2");
props.setProperty("namespace.iDontKnowThisNameAtCompileTime", "anothervalue");
props.setProperty("someStuff.morestuff", "stuff");
Map<String, String> filtered = new MapFilter(props, "namespace.");
System.out.println("namespace props " + filtered);
}
}
The accepted answer works in 99% of all the cases, but the devil is in the details.
Specifically, the accepted answer does not work when the map has a key which begins with the prefix, followed by Character.MAX_VALUE followed by anything else. Comments posted to the accepted answer yields small improvements, but still does not cover all of the cases.
The following solution also uses NavigableMap to pick out a sub map given a key prefix. The solution is the subMapFrom() method and the trick is to not bump/increment the last char of the prefix, rather, the last char which is not MAX_VALUE whilst cutting off all trailing MAX_VALUEs. So for example, if the prefix is "abc" we increment it to "abd". But if the prefix is "ab" + MAX_VALUE we drop the last char and bump the preceding char instead, resulting in "ac".
import static java.lang.Character.MAX_VALUE;
public class App
{
public static void main(String[] args) {
NavigableMap<String, String> map = new TreeMap<>();
String[] keys = {
"a",
"b",
"b" + MAX_VALUE,
"b" + MAX_VALUE + "any",
"c"
};
// Populate map
Stream.of(keys).forEach(k -> map.put(k, ""));
// For each key that starts with 'b', find the sub map
Stream.of(keys).filter(s -> s.startsWith("b")).forEach(p -> {
System.out.println("Looking for sub map using prefix \"" + p + "\".");
// Always returns expected sub maps with no misses
// [b, b, bany], [b, bany] and [bany]
System.out.println("My solution: " +
subMapFrom(map, p).keySet());
// WRONG! Prefix "b" misses "bany"
System.out.println("SO answer: " +
map.subMap(p, true, p + MAX_VALUE, true).keySet());
// WRONG! Prefix "b" misses "b" and "bany"
System.out.println("SO comment: " +
map.subMap(p, true, tryIncrementLastChar(p), false).keySet());
System.out.println();
});
}
private static <V> NavigableMap<String, V> subMapFrom(
NavigableMap<String, V> map, String keyPrefix)
{
final String fromKey = keyPrefix, toKey; // undefined
// Alias
String p = keyPrefix;
if (p.isEmpty()) {
// No need for a sub map
return map;
}
// ("ab" + MAX_VALUE + MAX_VALUE + ...) returns index 1
final int i = lastIndexOfNonMaxChar(p);
if (i == -1) {
// Prefix is all MAX_VALUE through and through, so grab rest of map
return map.tailMap(p, true);
}
if (i < p.length() - 1) {
// Target char for bumping is not last char; cut out the residue
// ("ab" + MAX_VALUE + MAX_VALUE + ...) becomes "ab"
p = p.substring(0, i + 1);
}
toKey = bumpChar(p, i);
return map.subMap(fromKey, true, toKey, false);
}
private static int lastIndexOfNonMaxChar(String str) {
int i = str.length();
// Walk backwards, while we have a valid index
while (--i >= 0) {
if (str.charAt(i) < MAX_VALUE) {
return i;
}
}
return -1;
}
private static String bumpChar(String str, int pos) {
assert !str.isEmpty();
assert pos >= 0 && pos < str.length();
final char c = str.charAt(pos);
assert c < MAX_VALUE;
StringBuilder b = new StringBuilder(str);
b.setCharAt(pos, (char) (c + 1));
return b.toString();
}
private static String tryIncrementLastChar(String p) {
char l = p.charAt(p.length() - 1);
return l == MAX_VALUE ?
// Last character already max, do nothing
p :
// Bump last character
p.substring(0, p.length() - 1) + ++l;
}
}
Output:
Looking for sub map using prefix "b".
My solution: [b, b, bany]
SO answer: [b, b]
SO comment: [b, b, bany]
Looking for sub map using prefix "b".
My solution: [b, bany]
SO answer: [b, bany]
SO comment: []
Looking for sub map using prefix "bany".
My solution: [bany]
SO answer: [bany]
SO comment: [bany]
Should perhaps be added that I also tried various other approaches including code I found elsewhere on the internet. All of them failed by yielding an incorrect result or out right crashed with various exceptions.
Remove all keys which does not start with your desired prefix:
yourMap.keySet().removeIf(key -> !key.startsWith(keyPrefix));
map's keyset has no a special structure so I think you have to check each of the keys anyway. So you can't find a way which will be faster than a single loop...
I used this code to do a speed trial:
public class KeyFinder {
private static Random random = new Random();
private interface Receiver {
void receive(String value);
}
public static void main(String[] args) {
for (int trials = 0; trials < 10; trials++) {
doTrial();
}
}
private static void doTrial() {
final Map<String, String> map = new HashMap<String, String>();
giveRandomElements(new Receiver() {
public void receive(String value) {
map.put(value, null);
}
}, 10000);
final Set<String> expressions = new HashSet<String>();
giveRandomElements(new Receiver() {
public void receive(String value) {
expressions.add(value);
}
}, 1000);
int hits = 0;
long start = System.currentTimeMillis();
for (String expression : expressions) {
for (String key : map.keySet()) {
if (key.startsWith(expression)) {
hits++;
}
}
}
long stop = System.currentTimeMillis();
System.out.printf("Found %s hits in %s ms\n", hits, stop - start);
}
private static void giveRandomElements(Receiver receiver, int count) {
for (int i = 0; i < count; i++) {
String value = String.valueOf(random.nextLong());
receiver.receive(value);
}
}
}
The output was:
Found 0 hits in 1649 ms
Found 0 hits in 1626 ms
Found 0 hits in 1389 ms
Found 0 hits in 1396 ms
Found 0 hits in 1417 ms
Found 0 hits in 1388 ms
Found 0 hits in 1377 ms
Found 0 hits in 1395 ms
Found 0 hits in 1399 ms
Found 0 hits in 1357 ms
This counts how many of 10000 random keys start with any one of 1000 random String values (10M checks).
So about 1.4 seconds on a simple dual core laptop; is that too slow for you?