Java Programming Tutorials

Java programming tutorials with many code examples!

Java List swap

Problem:

How to swap elements in Java List? Swap operation is very often used when implementing sorting. In the following example we show Java List swap operation from Java Collections Framework.

Solution:

In the following example we’ve implemented simple sorting in Java that is using swap operation extensively to order elements properly. As usual, we’ve reused great java.util.Collections to the actual work:

package com.farenda.java;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class CollectionsSwap {

    public static void main(String[] args) {
        List<Integer> items = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        Collections.shuffle(items);
        System.out.println("Ordered randomly: " + items);

        for (int i = 0, n = items.size(); i < n; ++i) {
            for (int j = i+1; j < n; ++j) {
                if (items.get(i) > items.get(j)) {
                    System.out.printf("Swap(%d,%d) = %2d <-> %2d%n",
                            i, j, items.get(i), items.get(j));
                    Collections.swap(items, i, j);
                }
            }
        }

        System.out.println("Sorted: " + items);
    }
}

Here we don’t have to wrap the list returned from Arrays.asList() into another one, because this implementation already supports set() operation.

Of course, Collections.swap(List, i, j) will throw IndexOutOfBoundsException when any of given indexes is out of bounds.

And here’s the Java sorting with Collections.swap() in action:

Ordered randomly: [2, 9, 7, 1, 3, 6, 4, 10, 5, 8]
Swap(0,3) =  2 <->  1
Swap(1,2) =  9 <->  7
Swap(1,3) =  7 <->  2
Swap(2,3) =  9 <->  7
Swap(2,4) =  7 <->  3
Swap(3,4) =  9 <->  7
Swap(3,5) =  7 <->  6
Swap(3,6) =  6 <->  4
Swap(4,5) =  9 <->  7
Swap(4,6) =  7 <->  6
Swap(4,8) =  6 <->  5
Swap(5,6) =  9 <->  7
Swap(5,8) =  7 <->  6
Swap(6,8) =  9 <->  7
Swap(7,8) = 10 <->  9
Swap(7,9) =  9 <->  8
Swap(8,9) = 10 <->  9
Sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

One thing worth noting is how Collections.swap() is implemented:

List l = list;
l.set(i, l.set(j, l.get(i)))

Instead of storing one value in a temporary variable it uses a feature of List.set() operation, which returns previous value and sets it in the other place. Nice one! :-)

Share with the World!