简体   繁体   中英

Get Keys and Value pair after removing an element from the key's list in a Map<List<String>, IInterface>

In my use case, there is an interface IInterface and a map of List as keys and IInterface as values.

public interface IInterface{
   ....
}

public MyClass{
    Map<List<Integer>, IInterface> interfaceByStringList;
    MyClass(){
        interfaceByStringList = new HashMap<List<Integer>,IInterface>();
    }

    //Method to remove one element from key list
    public Map<List<Integer>, IInterface> myMethod(IntegerelementToRemove){
        ................
    }
}

In the above scenario, I have to remove "elementToRemove" from list of keys where it is present in the keySet() of the Map. Then I have to return the updated Map.

For eg Map's KeySet is like this:

{[1,2,3],[4,7,5],[67],[23,41]}
and corresponding values: 
{IInterface1, IInterface2,IInterface3,IInterface4]

Suppose if I want to remove 4 then my updated map to return: Updated Map KeySet:

{[1,2,3],[7,5],[67],[23,41]}
and corresponding values: 
{IInterface1, IInterface2,IInterface3,IInterface4]

Take it:

interfaceByStringList
     .entrySet()
     .removeIf(entry -> entry.getKey().contains(elementToRemove));

This will work for you.

public Map<List<Integer>, IInterface> myMethod(int integerElementToRemove){
    interfaceByStringList
            .keySet()
            .stream()
            .filter(integers -> integers.contains(integerElementToRemove))
            .forEach(integers -> integers.remove(Integer.valueOf(integerElementToRemove)));
    return interfaceByStringList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM