Linked HashMap-Iteration(Java)

问题描述 投票:-2回答:3

我正在尝试通过Linked HashMap keySet进行迭代,但是我很难使其正常工作。

基本上,我正在搜索keySet来找到一个单词和另一个单词。如果第二个单词紧接在第一个单词之后,我希望返回true。这是我到目前为止所取得的进步。

for (String word : storedWords.keySet()) {

        value0++;

        if(word.equals(firstWord)){
            value1 = value0;
        }

        if(word.equals(secondWord)){
            value2 = value0;
        }

        int value3 = value2 - 1;
        if(value1 == value3){
            result = true;
            break;
        }
    }

编辑:

我已经解决了我的问题,并感谢所有提供帮助的人。当网站上有很多可用信息时,我为此致歉,但是我只是缺乏对它背后逻辑的理解。

java linkedhashmap
3个回答
0
投票
Map<String, String> map = ...
for (Map.Entry<String, String> entry : map.entrySet()) {
    System.out.println(entry.getKey() + "/" + entry.getValue());
}

0
投票

您可以通过将每个元素的索引存储在单独的映射中来避免对整个keySet进行迭代;那么您就可以测试两个键是否都存在并且索引之间是否相差1。为方便起见,请将两个映射都封装到一个对象中:

import java.util.*;

public class MapWithIndices<K, V> {
    private final Map<K, V> map = new LinkedHashMap<>();
    private final Map<K, Integer> indices = new HashMap<>();

    public V get(K k) {
        return map.get(k);
    }

    public V put(K k, V v) {
        V old = map.put(k, v);
        if(old == null) {
            indices.put(k, indices.size());
        }
        return old;
    }

    public boolean areAdjacent(K k1, K k2) {
        Integer i1 = indices.get(k1);
        Integer i2 = indices.get(k2);
        return i1 != null && i2 != null && i1 + 1 == i2;
    }
}

您可以将更多Map方法(例如size)委派给map,以添加更多方法。但是,remove方法无法有效实现,因为它需要重新计算所有后续索引。如果需要从地图上删除,则应考虑替代的数据结构设计;例如,indices可以存储每个键的原始插入顺序,而order statistic tree可以用来计算有多少个现有键的原始插入顺序较低。


0
投票

我认为这与您刚开始时的想法是一致的。您可能想要测试性能。

import java.util.LinkedHashMap;
import java.util.Map;

class Testing {
  Map<String, Integer> storedWords = new LinkedHashMap<>();
  {
    storedWords.put("One",1);
    storedWords.put("Two",2);
    storedWords.put("Three",3);
    storedWords.put("Four",4);
    storedWords.put("Five",5);
  }

  public static void main(String[] args) {
    Testing t = new Testing();
    String firstWord;
    String secondWord;

    firstWord = "Three";
    secondWord = "Five";
    System.out.println(t.consecutive(firstWord, secondWord)); // false

    firstWord = "Two";
    secondWord = "Three";
    System.out.println(t.consecutive(firstWord, secondWord)); // true
  }

  public boolean consecutive(String firstWord, String secondWord) {
    boolean foundfirst = false;  
    for (String word : storedWords.keySet()) {
      if (!foundfirst && word.equals(firstWord)){
        foundfirst = true;
        continue;
      }

      if (foundfirst) {
        if(word.equals(secondWord)){
          return true;
        } else {
          foundfirst = false; // reset to search for the first word again
        }
      }
    }
    return false;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.