Archives: List

Java – List Iterate Example

[code lang=”java”]import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class ArrayToList {

public static void main(String[] argv) {

String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };

// convert array to list
List<String> lList = Arrays.asList(sArray);

// iterator loop
System.out.println("#1 iterator");
Iterator<String> iterator = lList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

// for loop
System.out.println("#2 for");
for (int i = 0; i &lt; lList.size(); i++) {
System.out.println(lList.get(i));
}

// for loop advance
System.out.println("#3 for advance");
for (String temp : lList) {
System.out.println(temp);
}

// while loop
System.out.println("#4 while");
int j = 0;
while (j < lList.size()) {
System.out.println(lList.get(j));
j++;
}
}

}[/code]


Java – Rotate Elements of List

Following example uses rotate() method to rotate elements of the list depending on the 2nd argument of the method.

[code lang=”java”]import java.util.*;

public class Main {

public static void main(String[] args) {
List list = Arrays.asList("one Two three Four five six".split(" "));
System.out.println("List :"+list);
Collections.rotate(list, 3);
System.out.println("rotate: " + list);
}

}[/code]

Output:

List :[one, Two, three, Four, five, six]
rotate: [Four, five, six, one, Two, three]


Java – Convert Array to List

[code lang=”java”]import java.util.*;
import java.io.*;

public class ArrayToCollection {

public static void main(String args[]) throws IOException {

BufferedReader in = new BufferedReader
(new InputStreamReader(System.in));
System.out.println("How many elements you want to add to the array: ");
int n = Integer.parseInt(in.readLine());
String[] name = new String[n];
for(int i = 0; i < n; i++) {
name[i] = in.readLine();
}
List list = Arrays.asList(name);
System.out.println();
for(String li: list) {
String str = li;
System.out.print(str + " ");
}

}

}[/code]
Output:

How many elements you want to add to the array:
red white green

red white green