Search code examples
javaloopsdictionarytreemap

Remove entries with conditions in a treemap


I'm doing a Java practice, the question ask me to takes a provided TreeMap, removes entries where the key is a multiple of keyFilter and the value contains the valueFilter character, then returns the resulting TreeMap. If applying the key and value filters does not remove any entries, then the provided map must be returned.

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MapFilter {
    public static TreeMap<Integer, String> filterTreeMap(
            TreeMap<Integer, String> map, int keyFilter, char valueFilter) {
        
        TreeMap<Integer, String> finalMap = new TreeMap<Integer, String>();
        
        for(Map.Entry<Integer, String> e: finalMap.entrySet()){
            if(getKey() % keyFilter == 0 && getValue().equals(valueFilter){
                map.remove(getKey());
            }
        }
        return finalMap;
    }
}

This is the code I have so far. I didn't get how the treemap works and also how to compare the value contains the valueFilter character. I have error on my code. Any help would be nice. Thank you!


Solution

  • That would do the trick, explainations are in the code:

    public static TreeMap<Integer, String> filterTreeMap(TreeMap<Integer, String> map, int keyFilter, char valueFilter) {
        // <--- your finalMap was always empty, you have to fill values in it
        // so initialize it with your parameter map
        TreeMap<Integer, String> finalMap = new TreeMap<Integer, String>(map); 
    
        for(Map.Entry<Integer, String> e: map.entrySet()){
            if(e.getKey() % keyFilter == 0 && e.getValue().indexOf(valueFilter) >= 0){ 
                // <--- to test if a string contains a char, use index of
                finalMap.remove(e.getKey());
            }
        }
        return finalMap;
    }
    
    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<>();
        map.put(1, "abcdef");
        map.put(2, "fghijk");
        map.put(4, "fghijk");
        map.put(3, "lmnop");
    
        System.out.println(filterTreeMap(map, 2, 'f')); // output: {1=abcdef, 3=lmnop}
        System.out.println(filterTreeMap(map, 3, 'a')); // output: {1=abcdef, 2=fghijk, 3=lmnop, 4=fghijk}
    }