Java - Iterating over every two elements in a list

前端 未结 11 2089
梦毁少年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:09
    List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
    for(int i = 0; i < strings.size(); i++){
        if(i½2 = 0){
            String first = strings.get(i);
            System.out.print("First [" + first + "] ");
        }else{
             String second = strings.get(i + 1);
             System.out.println("- Second [" + second + "]");
        }
    }
    
    0 讨论(0)
  • 2020-12-19 05:10

    Just increase i by 2:

    for(int i = 0; i < strings.size(); i += 2) {
    
    0 讨论(0)
  • 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<String> 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){
        ...
    }
    
    0 讨论(0)
  • 2020-12-19 05:17
    for(int i = 0; i < strings.size(); i++){
        String first = strings.get(i++);
        String second = null;
        if(strings.size() > i){
            second = strings.get(i);
        }
        System.out.println("First [" + first + "] - Second [" + second + "]");
    }
    
    0 讨论(0)
  • 2020-12-19 05:23

    I created the following method using a Java8 BiConsumer:

    public static <T> void tupleIterator(Iterable<T> iterable, BiConsumer<T, T> consumer) {
        Iterator<T> it = iterable.iterator();
        if(!it.hasNext()) return;
        T first = it.next();
    
        while(it.hasNext()) {
            T next = it.next();
            consumer.accept(first, next);
            first = next;
        }
    }
    

    use it like this:

    List<String> myIterable = Arrays.asList("1", "2", "3");
    tupleIterator(myIterable, (obj1, obj2) -> {
        System.out.println(obj1 + " " + obj2);
    });
    

    This will output:

    1 2
    2 3
    
    0 讨论(0)
  • 2020-12-19 05:24

    You need to modify and increment i for the second value, modify the statement:

    second = strings.get(i + 1);
    

    to

    second = strings.get(++i);
    

    This will increment the i as well, since this seems to be the desired behaviour.

    So your code would be:

    List<String> strings = Arrays.asList("item 1", "item 2", "item 3", "item 4");
    for(int i = 0; i < strings.size(); i++){
        String first = strings.get(i);
        String second = null;
        if(strings.size() > i + 1){
            second = strings.get(++i); //Change here
        }
        System.out.println("First [" + first + "] - Second [" + second + "]");
    }
    
    0 讨论(0)
提交回复
热议问题