Java - Iterating over every two elements in a list

前端 未结 11 2088
梦毁少年i
梦毁少年i 2020-12-19 04:26

What\'s the best way to iterate over a list while processing 2 elements at the same time?

Example:

List strings = Arrays.asList(\"item          


        
11条回答
  •  囚心锁ツ
    2020-12-19 05:14

    For performance, I will recommend you to compute the size of the list only one and not create a new string at each new loop.

    List strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
    int length = strings.size();
    String first, second = null;
    for(int i = 0; i < length; i += 2){
        ...
    }
    

提交回复
热议问题