简体   繁体   English

检测最后一次 foreach 循环迭代

[英]detect last foreach loop iteration

Supposing that I have some foreach loop like this:假设我有一些这样的foreach循环:

Set<String> names = new HashSet<>();
//some code
for (String name: names) {
     //some code
}

Is there a way to check inside foreach that the actual name is the last one in Set without a counter?有没有办法在没有计数器的情况下检查foreach的实际名称是Set中的最后一个? I didn't found here some question like this.我没有在这里找到这样的问题。

For simplicity and understandability, imo, would do:为了简单和易懂,imo 会这样做:

Set<String> names = new HashSet<>();
Iterator<String> iterator = names.iterator();
    while (iterator.hasNext()) {
        String name = iterator.next();
        //Do stuff
        if (!iterator.hasNext()) {
            //last name 
        }
     }

Also, it depends on what you're trying to achieve.此外,这取决于您要实现的目标。 Let's say you are implementing the common use case of separating each name by coma, but not add an empty coma at the end:假设您正在实现通过 coma 分隔每个名称的常见用例,但未在末尾添加一个空的 coma:

Set<String> names = new HashSet<>();
names.add("Joao");
names.add("Pereira");

//if the result should be Joao, Pereira then something like this may work
String result = names.stream().collect(Collectors.joining(", "));

Other answears are completely adequate, just adding this solution for the given question.其他答案完全足够,只需为给定问题添加此解决方案即可。

Set<String> names = new HashSet<>();

   //some code
   int i = 0;

for (String name: names) {
    if(i++ == names.size() - 1){
        // Last iteration
    }
   //some code

}

There isn't, take a look at How does the Java 'for each' loop work?没有,看看Java 'for each' 循环是如何工作的?

You must change your loop to use an iterator explicitly or an int counter.您必须更改循环以显式使用迭代器或 int 计数器。

If you are working with a complex object and not just a plain list/set the below code might help.如果您正在处理一个复杂的对象,而不仅仅是一个简单的列表/设置,下面的代码可能会有所帮助。 Just adding a map function to actually get the desired string before you collect.只需添加一个映射函数即可在收集之前实际获取所需的字符串。

String result = violations.stream().map(e->e.getMessage()).collect(Collectors.joining(", "));

There is no build in method to check if the current element is also the last element.没有内置方法来检查当前元素是否也是最后一个元素。 Besides that you are using a HashSet which does not guarantee the return order.除此之外,您使用的是不保证退货顺序的HashSet Even if you want to check it eg with an index i the last element could always be a different one.即使您想检查它,例如使用索引i ,最后一个元素也可能总是不同的。

A Set does not guaranty order over of items within it. Set不保证其中的项目的顺序。 You may loop through the Set once and retrieve "abc" as the "last item" and the next time you may find that "hij" is the "last item" in the Set .您可以遍历Set一次并检索“abc”作为“最后一项”,下次您可能会发现“hij”是Set的“最后一项”。

That being said, if you are not concerned about order and you just want to know what the arbitrary "last item" is when observing the Set at that current moment, there is not built in way to do this.话虽如此,如果您不关心顺序,而只想知道在当前时刻观察Set时任意的“最后一项”是什么,则没有内置的方法可以做到这一点。 You would have to make use of a counter.您将不得不使用计数器。

.map(String::toString) from the answer above is redundant, because HashSet already contains String values.上面答案中的 .map(String::toString) 是多余的,因为 HashSet 已经包含 String 值。 Do not use Set to concatenate strings because the order is not assured.不要使用 Set 来连接字符串,因为顺序是不确定的。

List<String> nameList = Arrays.asList("Michael", "Kate", "Tom");
String result = nameList.stream().collect(Collectors.joining(", "));

There is an easy way you can do this throw one condition.有一种简单的方法可以做到这一点,抛出一个条件。 consider this is your array:考虑这是你的数组:

int odd[] = {1,3,5,7,9,11};

and you want to print it all in one line with " - " hyphen between them except the last one.并且您想将其全部打印在一行中,除了最后一个之外,它们之间用“ - ”连字符。

for(int aa:odd) {
    System.out.print(aa);
            
    if(odd[odd.length - 1] != aa)
        System.out.print(" - ");
}

this condition这种情况

if( odd[odd.length - 1] != aa )

will check if you aren't in the last element so you can still add " - ", otherwise you will not add it.将检查您是否不在最后一个元素中,因此您仍然可以添加“ - ”,否则您将不会添加它。

Yes, there is a way to check it inside of foreach , by use of a counter:是的,有一种方法可以通过使用计数器在foreach内部检查它:

Set<String> names = new HashSet<>();

int i = names.size() - 1;
for (String name: names) {
    if (i-- == 0) {
        // some code for last name
    }
    //some code
}

Consider, names.size() is called only one time outside of the loop.考虑一下, names.size()在循环外只被调用一次。 This makes the loop faster than processing it multiple times within the loop.这使得循环比在循环内多次处理它更快。

    List<String> list = Arrays.asList("1", "2", "3");
    for (String each : list) {
        if (list.indexOf(each) == (list.size() - 1)) {
            System.out.println("last loop");
        }
    }

Note: Set is NOT an ordered collection.注意:Set 不是有序集合。

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

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