How to shuffle a string in java

Posted by Marta on December 18, 2020 Viewed 1301 times

Learn how to shuffle a string in java in two different ways, using java 7 and java 8. Code Examples Included. Move the characters out of order.

Card image cap

Hey there! This article will see how to shuffle a string in java in two different ways, using java 7 and java 8. In other words, move every character in the string out of order. For instance:

Input: hello
Output: ohell  

Using java7

Here is how to shuffle a string in java 7. First, you will need to place every character in a List structure(lines 7 to 10). Next, you will select a random character from this list and add it to the new string you are building. See this in action below:

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class ShuffleString { 
	public static String shuffleJava7(String text) {
        List<Character> characters = new LinkedList<>();
        for(char c:text.toCharArray()){
            characters.add(c);
        }
        StringBuilder result = new StringBuilder();
        for (int index=0;index<text.length();index++){
            int randomPosition = new Random().nextInt(characters.size());
            result.append(characters.get(randomPosition));
            characters.remove(randomPosition);
        }
        return result.toString();
    }
}

Using java8

In java 8, you can follow the same mechanism as before but taking advantage of the stream feature. Streams will allow you to loop through a collection without using a loop. See the code below:

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ShuffleString {    
	public static String shuffleJava8(String text){
        List<Character> characters =  text.chars().mapToObj( c -> (char)c).collect(Collectors.toList());
        StringBuilder result = new StringBuilder();
        IntStream.range(0,text.length()).forEach((index) -> {
            int randomPosition = new Random().nextInt(characters.size());
            result.append(characters.get(randomPosition));
            characters.remove(randomPosition);
        });
        return result.toString();
    }
}

If you like to test your code, you can add a main method to your code like the one below. Make sure you add this method inside a class.

	public static void main(String[] args){
        System.out.println(shuffleJava7("programming is awesome"));
        System.out.println(shuffleJava8("hello code rocks"));
    }

You can also test this code using a JUnit test and therefore automate your testing. This way, every time you change your code, you only need to run the test to make sure the code still works correctly. See an example of how to create a JUnit test below:

import org.junit.Assert;
import org.junit.Test;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ShuffleStringTest {

    @Test
    public void test(){
        String originalText = "hello code rocks";
        String shuffledText = ShuffleString.shuffleJava7(originalText);
        List<Character> originalCharacters = originalText.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
        List<Character> shuffledCharacters = shuffledText.chars().mapToObj(c -> (char)c).collect(Collectors.toList());
        originalCharacters.sort(Comparator.naturalOrder());
        shuffledCharacters.sort(Comparator.naturalOrder());
        Assert.assertEquals(originalCharacters, shuffledCharacters);
    }
}

This test will make sure the shuffled text contains precisely the same characters as the original text.

Conclusion

To summarise, in this tutorial, we have seen how to shuffle a string in java, using java 7, and also using java 8. And how you can implement this task just using java. Plus, no third-party libraries are necessary. I hope you enjoy this tutorial and Happy Coding!

More interesting articles

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java