Alvin
Alvin

Reputation: 8499

How to get pairs of consecutive value in a list?

I want to get pairs of consecutive values by looping through an array:

List values = Arrays.asList("A", "B", "C");
ListIterator<String> it = values.listIterator();
while(it.hasNext()) {
      String start = it.previous();
      String end = it.next();
}

How do I get:

A, B
B, C

Upvotes: 0

Views: 1451

Answers (4)

Level_Up
Level_Up

Reputation: 824

If you use Java 8 or bigger version you also can try:

public static void main(String[] args) {
    List<String> values = Arrays.asList("A", "B", "C");

    IntStream.range(0, values.size() - 1)
        .forEach(i -> System.out.println(values.get(i) + ", " + values.get(i + 1)));

}

Here it is used Stream which will loop from 0 (inclusive) to values.size() - 1 (exclusive) and after that it is used forEach which accept Consumer with one argument (in this case the looping integer) and after that just print the result. I know that it is almost the same as iterative loop but I want to show that it can be made also this way.

Good luck!

Upvotes: 0

jokster
jokster

Reputation: 577

How about simply storing the previous value in a local var:

List<String> values = Arrays.asList("A", "B", "C");
Iterator<String> it = values.iterator();
if (it.hasNext()) {
    String start = it.next();
    for(String end = null; it.hasNext(); start = end) {
      end = it.next();
    }
}

Upvotes: 1

Matteo Tomai
Matteo Tomai

Reputation: 174

Try this :)

List<String> values = Arrays.asList("A", "B", "C");
ListIterator<String> it = values.listIterator();
while(it.hasNext()) {
    String start = it.next();
    if(it.hasNext()) {
        String end = it.next();
        it.previous();
        System.out.println(start + end);
    }
}

Upvotes: 4

deHaar
deHaar

Reputation: 18568

You can achieve that with a classic for loop like this:

public static void main(String[] args) {
    List<String> values = Arrays.asList("A", "B", "C");
    /*
     * You obviously want to output 2 values per iteration,
     * that means you have to adjust the condition to iterate to the
     * second last index (because of accessing i + 1)
     */
    for (int i = 0; i < values.size() - 1; i++) {
        System.out.println(values.get(i) + ", " + values.get(i + 1));
    }
}

There is no need for an iterator and I strongly recommend not using just List (raw type) but List<String> (specifying item type).

Upvotes: 5

Related Questions