Skip to content

Yet another programming solutions log

Sample bits from programming for the future generations.

Technologies Technologies
  • Algorithms and Data Structures
  • Java Tutorials
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Spock Framework Tutorial
  • Spring Framework
  • Bash Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Developer’s Tools
  • Productivity
  • About
Expand Search Form

Java List swap

farenda 2015-08-14 0

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!
Categories Java Tags java-collections
Previous: Java sort List
Next: Java synchronized List

Recent Posts

  • Java 8 Date Time concepts
  • Maven dependency to local JAR
  • Caesar cipher in Java
  • Java casting trick
  • Java 8 flatMap practical example
  • Linked List – remove element
  • Linked List – insert element at position
  • Linked List add element at the end
  • Create Java Streams
  • Floyd Cycle detection in Java

Pages

  • About Farenda
  • Algorithms and Data Structures
  • Bash Tutorial
  • Bean Validation Tutorial
  • Clojure Tutorial
  • Design Patterns
  • Java 8 Streams and Lambda Expressions Tutorial
  • Java Basics Tutorial
  • Java Collections Tutorial
  • Java Concurrency Tutorial
  • Java IO Tutorial
  • Java Tutorials
  • Java Util Tutorial
  • Java XML Tutorial
  • JUnit Tutorial
  • MongoDB Tutorial
  • Quartz Scheduler Tutorial
  • Software Developer’s Tools
  • Spock Framework Tutorial
  • Spring Framework

Tags

algorithms bash bean-validation books clojure design-patterns embedmongo exercises git gof gradle groovy hateoas hsqldb i18n java java-basics java-collections java-concurrency java-io java-lang java-time java-util java-xml java8 java8-files junit linux lists log4j logging maven mongodb performance quartz refactoring regex rest slf4j solid spring spring-boot spring-core sql unit-tests

Yet another programming solutions log © 2022

sponsored