1

小さなアプリケーションで、ハッシュマップ内の特定のキーのみを出力するようにしようとしています (「不要な」文字列は含まれていません)。私がこれを試みた方法を以下に示します。

Map<String, Integer> items = new HashMap<String, Integer>();

    String[] unwanted = {"hi", "oat"};

    items.put("black shoes", 1);
    items.put("light coat", 10);
    items.put("white shoes", 40);
    items.put("dark coat", 90);

    for(int i = 0; i < unwanted.length; i++) {
        for(Entry<String,Integer> entry : items.entrySet()) {
            if(!entry.getKey().contains(unwanted[i])) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
        }
    }

それでも、これを出力します:

dark coat = 90
black shoes = 1
light coat = 10
white shoes = 40
black shoes = 1

ただし、代わりにこれを出力することを意図しています (「hi」と「oat」を含むキーは省略されるはずなので、そのままにしておく必要があります:)

black shoes = 1

なぜ私が障害を見落としているのかわかりませんが、うまくいけば誰かが私にそれを指摘するのを手伝ってくれるでしょう.

4

3 に答える 3

1

If you see your outer loop:

for(int i = 0; i < unwanted.length; i++)

then it iterates thru

String[] unwanted = {"hi", "oat"};

Your map is as:

"dark coat" : 90
"white shoes": 40
"light coat" : 10
"black shoes", 1

Hence in first iteration,

unwanted[i]="hi"

So your inner loop does not print "white shoes" and rather it prints:

dark coat = 90
black shoes = 1
light coat = 10

as they do not contain "hi"

In the second interation,

unwanted[i]="oat"

So your inner loop does not print "dark coat" and "light coat" and prints the remaining from the map:

white shoes = 40
black shoes = 1

Thus you are getting the combined output of above two iterations as:

dark coat = 90
black shoes = 1
light coat = 10
white shoes = 40
black shoes = 1

So what you can do is try this code in which the inner loop and outer loops are flipped:

Map<String, Integer> items = new HashMap<String, Integer>();

    String[] unwanted = {"hi", "oat"};
    items.put("black shoes", 1);
    items.put("light coat", 10);
    items.put("white shoes", 40);
    items.put("dark coat", 90);

    boolean flag;
    for(Map.Entry<String,Integer> entry : items.entrySet()) {
        if(!stringContainsItemFromList(entry.getKey(),unwanted))
            System.out.println(entry.getKey() + " = " + entry.getValue());
    }

In above code, we have used static function:

public static boolean stringContainsItemFromList(String inputString, String[] items)
    {
        for(int i =0; i < items.length; i++)
        {
            if(inputString.contains(items[i]))
            {
                return true;
            }
        }
        return false;
    }

Hope that helped!!

于 2013-08-01T11:39:01.167 に答える