简体   繁体   English

从树状图中删除元素

[英]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.我已经编写了一个代码,它采用一个整数数组,但我无法找出一种方法来删除获得 (false) 值的树状图元素。 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.没有有效的方法来定位具有给定值的所有Map条目并删除它们。 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.首先要避免将它们放在Map中。 Instead of putting the characters of the first String with false value in the Map , put them in a separate Set :而不是将第一个带有false值的String的字符放在Map ,而是将它们放在单独的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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