【问题标题】:Iterating a HashMap with a condition使用条件迭代 HashMap
【发布时间】:2014-08-24 11:37:39
【问题描述】:

首先,对不起我的英语。

我从 Android 开始,但我遇到了 LinkedList 的问题。我想在迭代器中放置一个条件,但是当条件OK时,迭代器只显示一个映射条目(HashMap有键和值,但是(这很奇怪)当条件不验证时( system.out.println 在 if 之外)它显示了 HashMap 的 2 个值。

谁能帮帮我?

非常感谢。

(数据是一个LinkedList)

private void setDataBuscar(LinkedList<HashMap<String, String>> data){

        HashMap<String, String> hm = new HashMap<String, String>();        


        Iterator it = data.iterator();
        while(it.hasNext()) {

            hm = (HashMap) it.next();


            Iterator empleos = hm.entrySet().iterator();
            Map.Entry empleo;

            while (empleos.hasNext()) {
                empleo = (Map.Entry) empleos.next();

                
                String valor = empleo.getValue().toString();
                String llave = empleo.getKey().toString();//-->here llave have value

                
                system.out.println(valor+" "+llave);//--> here shows all dates(TITLE LINK)
                //  of the hasmap, without filter
  
                if(valor.contains(aBuscar)){
                    System.out.println(valor);
                    System.out.println(llave);//--> here dont shows llave ???
                }
                
                        
              }

【问题讨论】:

  • but when the condition not validate (the system.out.println is outside the if) 是什么意思?你的意思是如果你删除if(valor.contains(aBuscar)) 检查,那么两个条目都会被打印?这怎么好奇?您想要打印任何数据而不进行任何过滤程序吗?请重写您的问题以澄清您的问题。
  • 嗨 Jens,我会举个例子,可能会更好,我很难用英语解释。 hasmap 有 示例(汽车,轮胎)....很多这样,如果我尝试仅显示具有 "汽车" 的条目,则在迭代器内部会设置一个条件 if(map.getkey.contains ("car"){Toast.make...."key"+map.getkey+"values"+map.getvalue,它应该显示"汽车轮胎",但只显示"汽车"。如果我探测没有条件正确显示所有值。

标签: android data-structures iterator


【解决方案1】:

我解释您的评论,您希望循环遍历列表并打印当前所选实体的每个标题链接对,其中标题包含单词car(或在您的代码中aBuscar)。如果这是正确的,这是实现此行为的代码:

存储单个标题-链接对的类:

public class TitleLink {

  private String title;
  private String link;

  public TitleLink() {
    this.title = "";
    this.link = "";
  }

  public TitleLink(String title) {
    this.title = title;
    this.link = "";
  }

  public TitleLink(String title, String link) {
    this.title = title;
    this.link = link;
  }

  public boolean titleContains(String title) {
    return this.title.contains(title);
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getLink() {
    return link;
  }

  public void setLink(String link) {
    this.link = link;
  }

  @Override
  public String toString() {
    return "TitleLink {title=" + title + ", link=" + link + "}";
  }
}

测试类:

public class Test {

  private static String aBuscar = "car";

  public static void main(String[] args) {
    List<TitleLink> example = new LinkedList<>();

    example.add(new TitleLink("carTitle", "firstCarLink"));
    example.add(new TitleLink("carrotTitle", "firstCarrotLink"));
    example.add(new TitleLink("bikeTitle", "bikeCarLink"));
    example.add(new TitleLink("boatTitle", "boatCarLink"));

    example.add(new TitleLink("carTitle", "secondCarLink"));
    example.add(new TitleLink("carrotTitle", "secondCarrotLink"));
    example.add(new TitleLink("bikeTitle", "secondCarLink"));
    example.add(new TitleLink("boatTitle", "secondCarLink"));

    setDataBuscar(example);
  }

  private static void setDataBuscar(List<TitleLink> data) {
    System.out.println("------");
    System.out.println(data); // -> probe ... show whole content of the map
    System.out.println("------");

    for (TitleLink titleLink : data) {
      if (titleLink.titleContains(aBuscar)) {
        System.out.println(titleLink);
      }
    }
  }

  /*
   * This version stores the current title and link in separate variable inside the loop
   * and prints them if the condition is met.
  private static void setDataBuscar(List<TitleLink> data) {
    System.out.println("------");
    System.out.println(data); // -> probe ... show whole content of the map
    System.out.println("------");

    for (TitleLink titleLink : data) {
      String title = titleLink.getTitle();
      String link = titleLink.getLink();

      if (titleLink.titleContains(aBuscar)) {
        System.out.println(title);
        System.out.println(link);
      }
    }
  }*/

}

输出:

------
// all entries
------
TitleLink {title=carTitle, link=firstCarLink}
TitleLink {title=carrotTitle, link=firstCarrotLink}
TitleLink {title=carTitle, link=secondCarLink}
TitleLink {title=carrotTitle, link=secondCarrotLink}

更改解析器类:

public class Parser {

    private URL url;
    static TitleLink entry2;

    public Parser(String url) {
        try {
            this.url = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public List<TitleLink> parse() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        List<TitleLink> entries = new LinkedList<>();
        TitleLink entry;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(this.url.openConnection().getInputStream());
            Element root = dom.getDocumentElement();
            NodeList items = root.getElementsByTagName("item");
            for (int i=0;i<items.getLength();i++){
                entry = new TitleLink();
                Node item = items.item(i);
                NodeList properties = item.getChildNodes();
                for (int j=0;j<properties.getLength();j++) {
                    Node property = properties.item(j);
                    String name = property.getNodeName();
                    if (name.equalsIgnoreCase("title")){
                      entry.setTitle(property.getFirstChild().getNodeValue());
                    } else if (name.equalsIgnoreCase("link")){
                      entry.setTitle(property.getFirstChild().getNodeValue());
                      entries.add(entry);
                      entry = new TitleLink();
                    }
                }
                //entries.add(entry);
                entry2=entry;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return entries;
    }
}

我无法测试解析器类的变化,因为我没有包含该类应该解析的数据的网页。如果您测试它并发现任何错误,您可以尝试修复它们(不应该太难)或发表评论。

【讨论】:

  • 首先感谢您的努力和时间。我尝试了你的类,但我无法实现它们,因为应用程序的其他功能停止工作。但我将它们保留在一个从头开始的应用程序中。还有一件事:) .... 如果 LinkedList 由键“T”或“L”成对保存(最终静态字符串 DATA_TITLE = “T”;静态最终字符串 DATA_LINK = “ L") 和值,例如:{T, 422884/0 PEONES INDUSTRY OF A ....}, {L, http://www.webpage.com .......} .
  • 执行“while empleos.hasNext()”的每一步都会显示一个数字,第一个,然后是一个LINK TITLE,所以如果没有,因为一次只有一件事。如果你把计数器放在里面,一会儿就会看到。有没有办法在满足条件的情况下也保存以下内容? , 在两个不同的字符串变量中。
  • 如果你不能花更多的时间来学习这个学习者会理解并将作为解决方案验证你提供给我的,如果有人可以使用它。我已经厌倦了尝试这种方法。非常感谢和问候。
  • 我已经稍微更新了答案。我添加了另一个版本的setDataBuscar 方法,其中局部变量用于存储标题和链接。请检查这是否符合您的期望。不用担心我仍然想帮助你:)。
  • 终于!!! ,我修改了我的主要代码并使用了你的 TitleLink 类,我的主要问题已经解决了。现在我必须解决一些小问题,但我想我可以解决它,(我希望:))。非常感谢您的耐心等待,并确保您会在这个论坛上再次见到我 (jeje)。
【解决方案2】:

这是解析器类 Tom

公共类解析器{

private URL url;
static HashMap<String, String> entry2;

public Parser(String url) {
    try {
        this.url = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
}

public LinkedList<HashMap<String, String>> parse() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    LinkedList<HashMap<String, String>> entries = new LinkedList<HashMap<String, String>>();
    HashMap<String, String> entry;
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document dom = builder.parse(this.url.openConnection().getInputStream());
        Element root = dom.getDocumentElement();
        NodeList items = root.getElementsByTagName("item");
        for (int i=0;i<items.getLength();i++){
            entry = new HashMap<String, String>();
            Node item = items.item(i);
            NodeList properties = item.getChildNodes();
            for (int j=0;j<properties.getLength();j++){
                Node property = properties.item(j);
                String name = property.getNodeName();
                if (name.equalsIgnoreCase("title")){
                    entry.put(PortadaActivity.DATA_TITLE, property.getFirstChild().getNodeValue());
                } else if (name.equalsIgnoreCase("link")){
                    entry.put(PortadaActivity.DATA_LINK, property.getFirstChild().getNodeValue());
                }
            }
            entries.add(entry);
            entry2=entry;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return entries;
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多