-1

I wanted to get a submap from predicateMap:

I have tried this:

public class first {

public static void main(String[] args)
{
    TreeMap<String, String> myMap = new TreeMap<String, String>();
    Predicate onlyStrings = new InstanceofPredicate( String.class );
    myMap.put("Key1","1");
    myMap.put("Key2","2");
    myMap.put("Key3","3");
    
    System.out.println("Before using submap: "+ myMap );
    
    Predicate pred1 = new EqualPredicate( "1" );
    Predicate pred2 = new EqualPredicate( "2" );
    
    Predicate rule = new OrPredicate( pred1, pred2 );
    
    Map map = PredicatedMap.decorate( myMap, onlyStrings, rule ); 
    

    System.out.println("Before using submap: "+ map );
        
}

I am not able to get the desired submap which is the following:

Initial Map: {key1=1, key2=2, key3=3}

Output (submap): {key2=2, key3=3}

Can someone please help with this

  • 1
    Looking at the docs of `PredicatedMap`, it doesn't look like it's built to do what you're trying to do with it. It's not _supposed_ to get you submaps, it's supposed to build maps that apply constraints to new data. – Louis Wasserman Aug 20 '22 at 19:28

1 Answers1

0

It doesn't seems PredicatedMap do what you want to achive. It looks more like a validator when adding new values to map.

If you want to extract some values from a map base on predicate, Stream API from JDK should be enough.

If doesn't bother you to modify initial list:

 myMap.entrySet().removeIf( e -> !(e.getValue().equals("1") || e.getValue().equals("2")));

If you want to keep initial list and create a new one:

Map<String, String> collect = myMap.entrySet().stream().filter(x -> x.getValue().equals("1") || x.getValue().equals("2"))
                .collect(Collectors.toMap(e -> e.getKey(),e -> e.getValue()));

If you have a bigger list of value that you want to keep, you can create a set of them:

Set<String>  values = Set.of("1","2");

and filter base on this set:

collect = myMap.entrySet().stream().filter(x -> values.contains(x.getValue()))
                .collect(Collectors.toMap(e -> e.getKey(),e -> e.getValue()));

Or for the case with modifying initial list:

myMap.entrySet().removeIf( e -> !values.contains(e.getValue()));

Looks a bit clear if you extract values to keep as a set in my opinion.

Dorin Simion
  • 131
  • 5