Java 如何将此forEach转换为forLoop

Java 如何将此forEach转换为forLoop,java,for-loop,Java,For Loop,嘿,我正在尝试将我所有的foreach转换成ForLoops,因为我现在使用的是一个链表。 由于某种原因,我在这件事上遇到了麻烦!有人能把forEach变成forLoop吗 public String listCounty(String county) { boolean matchFound = false; int i = 0; String displayPropertys = "All Propertys"; for (Property item : h

嘿,我正在尝试将我所有的foreach转换成ForLoops,因为我现在使用的是一个链表。 由于某种原因,我在这件事上遇到了麻烦!有人能把forEach变成forLoop吗

public String listCounty(String county) {
    boolean matchFound = false;
    int i = 0;
    String displayPropertys = "All Propertys";

    for (Property item : house) {
        if (item.getGeneralLocation().equals(county)) {
            displayPropertys += "\n" + i++ + item;
            i++;
            matchFound = true;
        } else i++;
    }

    if (!matchFound)
        return "No propertys for this County";
    else
        return displayPropertys;
}

}

根据你的问题,我假设house是一个LinkedList

假设house是LinkedList,您可以使用LinkedList.getint,但使用传统的迭代器效率更高,因为访问LinkedList的任意索引可能会非常昂贵。您也可以使用细木工。大概

public String listCounty(String county) {
    boolean matchFound = false;
    Iterator<Property> iter = house.iterator();
    StringJoiner sj = new StringJoiner(System.lineSeparator());
    sj.add("All Propertys");
    for (int i = 0; iter.hasNext(); i++) {
        Property item = iter.next();
        if (item.getGeneralLocation().equals(county)) {
            sj.add(String.format("%d%s", i + 1, item));
            matchFound = true;
        }
    }
    return !matchFound ? "No propertys for this County" : sj.toString();
}

您应该能够使用以下方法来完成它

for(int index = 0; index < house.size(); index++)
{
    Property item = house.get(index);
    // Your code goes here
}
现在我们有了for循环中的索引,也就不需要i变量了

public String listCounty(String county) {
    boolean matchFound = false;
    String displayPropertys = "All Propertys";

    for (int index = 0; index < house.length; index++) {
        Property item = house.get(index)
        if (item.getGeneralLocation().equals(county)) {
            displayPropertys += "\n" + (index + 1) + item;
            matchFound = true;
        } 
    }

    if (!matchFound)
        return "No propertys for this County";
    else
        return displayPropertys;
}
您也可以使用像Elliot建议的迭代器。这将为您提供更好的性能,但更难阅读

Iterator<Property> iterator = house.iterator();
for (int index = 0; iterator.hasNext(); index++) {
    Property item = iterator.next();
    // Your code goes here
}
笔记你们在比赛中有两次我。
Iterator<Property> iterator = house.iterator();
for (int index = 0; iterator.hasNext(); index++) {
    Property item = iterator.next();
    // Your code goes here
}