Basic operations: in List Part III

Iterating over a list

Basically, we can use the enhanced for loop to iterate through all elements in the list, as follows:

1
2
3
for (String element : listStrings) {
    System.out.println(element);
}

Or use an iterator like this:

1
2
3
4
5
Iterator<String> iterator = listStrings.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

For more list-specific, use a list iterator as shown below:

1
2
3
4
5
Iterator<Number> iterator = linkedNumbers.listIterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

Since Java 8, we can use the forEach()method like this:

1
listStrings.forEach(s -> System.out.println(s));

5. Searching for an element in a list

To search for position of a specific element in the list or to know if the list contains the specified element, the following methods can be used:

    • boolean contains(Object): returns true if the list contains the specified element.
    • int indexOf(Object): returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
    • int lastIndexOf(Object): returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.

Examples:

1
2
3
4
5
6
7
8
9
if (listStrings.contains("Hello")) {
    System.out.println("Found the element");
} else {
    System.out.println("There is no such element");
}
int firstIndex = linkedNumbers.indexOf(1234);
int lastIndex = listStrings.indexOf("Hello");

Note that the above methods compare the elements using their equals() method, so if you define your own type, make sure it implements the equals() method correctly.

6. Sorting a list

The simplest way to sort out elements in a list is using the Collections.sort() static method which sorts the specified list into ascending order, based on the natural ordering of its elements. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
List<String> listStrings = new ArrayList<String>();
listStrings.add("D");
listStrings.add("C");
listStrings.add("E");
listStrings.add("A");
listStrings.add("B");
System.out.println("listStrings before sorting: " + listStrings);
Collections.sort(listStrings);
System.out.println("listStrings after sorting: " + listStrings);

Output:

1
2
listStrings before sorting: [D, C, E, A, B]
listStrings after sorting: [A, B, C, D, E]

Note that all elements in the list must implement the Comparable interface, so if you define your own type, make sure it implements that interface and its compareTo() method.

7. Copying one list into another

The Collections.copyList(dest, src) static method allows us to copy all elements from the source list into the destination one. Note that the destination list must be large enough to contain the entire source list. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
List<String> sourceList = new ArrayList<String>();
sourceList.add("A");
sourceList.add("B");
sourceList.add("C");
sourceList.add("D");
List<String> destList = new ArrayList<String>();
destList.add("V");
destList.add("W");
destList.add("X");
destList.add("Y");
destList.add("Z");
System.out.println("destList before copy: " + destList);
Collections.copy(destList, sourceList);
System.out.println("destList after copy: " + destList);

The output would be:

1
2
destList before copy: [V, W, X, Y, Z]
destList after copy: [A, B, C, D, Z]

8. Shuffling elements in a list

To randomly permute elements in a list, use the Collections.shuffle() static method. Here’s a quick example:

1
2
3
4
5
6
7
8
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) numbers.add(i);
System.out.println("List before shuffling: " + numbers);
Collections.shuffle(numbers);
System.out.println("List after shuffling: " + numbers);

The output would be:

1
2
List before shuffling: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after shuffling: [6, 4, 5, 0, 1, 3, 9, 7, 2, 10, 8]

 

9. Reversing elements in a list

To reverse order of elements in a list, use the Collections.reverse() static method. Here’s a quick example:

1
2
3
4
5
6
7
8
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i <= 10; i++) numbers.add(i);
System.out.println("List before reversing: " + numbers);
Collections.reverse(numbers);
System.out.println("List after reversing: " + numbers);

The output would be:

1
2
List before reversing: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
List after reversing: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

10. Extracting a portion of a list

The subList(fromIndex, toIndex) allows us to get a portion of the list between the specified fromIndex (inclusive) and toIndex (exclusive). Here’s an example:

1
2
3
4
5
List<String> listNames = Arrays.asList("Tom", "John", "Mary", "Peter", "David", "Alice");
System.out.println("Original list: " + listNames);
List<String> subList = listNames.subList(2, 5);
System.out.println("Sub list: " + subList);

Output:

1
2
Original list: [Tom, John, Mary, Peter, David, Alice]
Sub list: [Mary, Peter, David]

Note that the sub list is just a view of the original list, so any modifications made on the original list will reflect in the sub list.

11. Converting between Lists and arrays

The Java Collection Framework allows us to easily convert between lists and arrays.The Arrays.asList(T… a) method converts an array of type T to a list of type T. Here’s an example:

1
2
3
4
5
6
List<String> listNames = Arrays.asList("John", "Peter", "Tom", "Mary", "David", "Sam");
List<Integer> listNumbers = Arrays.asList(1, 3, 5, 7, 9, 2, 4, 6, 8);
System.out.println(listNames);
System.out.println(listNumbers);

Output:

1
2
[John, Peter, Tom, Mary, David, Sam]
[1, 3, 5, 7, 9, 2, 4, 6, 8]

And the List interface provides the toArray() method that returns an array of Objects containing all of the elements in the list in proper sequence (from first to last element). Here’s an example:

1
2
3
4
List<String> listWords = new ArrayList<String>();
// add elements to the list
Object[] arrayWords = listWords.toArray();

And the toArray(T[] a) method returns an array of type T, for example:

1
2
String[] words = listWords.toArray(new String[0]);
Integer[] numbers = listNumbers.toArray(new Integer[0]);

Note that the returned array contains copies of elements in the list, which that means we can safely modify the array without affecting the list.

12. Concurrent lists

By default, ArrayList and LinkedList are not thread-safe, so if you want to use them in concurrent context, you have to synchronize them externally using the Collections.synchronizedList() static method which returns a synchronized list that wraps the specified list. For example:

1
2
List<Object> unsafeList = new ArrayList<Object>();
List<Object> safeList = Collections.synchronizedList(unsafeList);

Note that you must manually synchronize the returned list when iterating over it, for example:

1
2
3
4
5
6
synchronized (safeList) {
    Iterator<Object> it = safeList.iterator();
    while (it.hasNext()) {
        System.out.println(it.next());
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: