简体   繁体   中英

Removing elements from treemap

i have written a code which takes an array of integer and i am unable to figure out a way to remove the treemap elements which got (false) value. Any help would be appreciated. the code is as.

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner s=new Scanner(System.in);
        int x=s.nextInt();
        String[] str=new String[x];
        for(int i=0;i<x;i++)
        {
            str[i]=s.next();
        }
        TreeMap<Character, Boolean> store=new TreeMap<Character, Boolean>();
        for(int i=0;i<str[0].length();i++)
        {
            store.put(str[0].charAt(i), false);
        }
        for(int i=1;i<str.length;i++)
        {
            for(int j=0;j<str[i].length();j++)
            {
                if(store.containsKey(str[i].charAt(j)))
                {
                    store.put(str[i].charAt(i), true);
                }
            }
                //code for removing elements from treemap with false value.
        }
    }
}

There is no efficient way to locate all the Map entries having a given value and removing them. You would have to iterate over all the entries in order to do that.

However, you don't have to do it. Just avoid putting them in the Map in the first place. Instead of putting the characters of the first String with false value in the Map , put them in a separate Set :

Map<Character, Boolean> store = new TreeMap<>();
Set<Character> set = new TreeSet<>();
for(int i=0;i<str[0].length();i++)
{
    set.add(str[0].charAt(i));
}
for(int i=1;i<str.length;i++)
{
    for(int j=0;j<str[i].length();j++)
    {
        if(set.contains(str[i].charAt(j)))
        {
            store.put(str[i].charAt(i), true);
        }
    }
}

如果您有一个TreeMap并且想要删除所有错误值,则可以使用 Java 8 中的 lambda 使用 oneliner 来实现。

map.entrySet().removeIf(entry -> !entry.getValue()); // getValue() will return a boolean

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