Nitu08 Nitu08 - 7 months ago 11
Java Question

How to get the required combination of two numbers from an arraylist?

I have an ArrayList of some elements

path = [1, 2, 5, 7]
. Now I want to get values from these elements like:

1,2
2,5
5,7


I used list iterator for this purpose, but what I am getting is:

1,2
2,2
5,7
7,7


I have seen this answer:
how to get all combination of an arraylist?
But I don't need all the combinations like this.

My code is:

public class iterator {

public static void main(String[] args){
ArrayList<String> path=new ArrayList<>();
path.add("1");
path.add("2");
path.add("5");
path.add("7");

System.out.println(path);
ListIterator<String> itr = path.listIterator();
while(itr.hasNext())
{
System.out.println(itr.next()+ "," + itr.next());
System.out.println(itr.previous()+ "," + itr.next());
}

}

}


My question is how can I get my required result?

Answer
for (int i = 0; i < path.size() - 1; i++) {
    System.out.println(path.get(i) + "," + path.get(i + 1));
}
Comments