Over a million developers have joined DZone.

Java String Permutations Code Snippet

A code snippet to show string permutations in Java to show all combinations of six characters.

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

Here is the Java code for String Permutations Or All combinations to its length.

package com.bos;

import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

public class StringPermutation {
private static Set<String> set = new ConcurrentSkipListSet<String>();

public static void permutation(String str) {
permutation("", str);
}

private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) {
set.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permutation(prefix + str.charAt(i),
str.substring(0, i) + str.substring(i + 1, n));
}
}
}

public static void main(String[] args) {
permutation("bosco");
for (String s : set) {
System.out.println(s);
}
}

}

It gives these 60 unique combinations as output:

bcoos
bcoso
bcsoo
bocos
bocso
boocs
boosc
bosco
bosoc
bscoo
bsoco
bsooc
cboos
cboso
cbsoo
cobos
cobso
coobs
coosb
cosbo
cosob
csboo
csobo
csoob
obcos
obcso
obocs
obosc
obsco
obsoc
ocbos
ocbso
ocobs
ocosb
ocsbo
ocsob
oobcs
oobsc
oocbs
oocsb
oosbc
ooscb
osbco
osboc
oscbo
oscob
osobc
osocb
sbcoo
sboco
sbooc
scboo
scobo
scoob
sobco
soboc
socbo
socob
soobc
soocb

Now I've done one in Java 8:

https://dzone.com/articles/java-18-string-unique-permutations-in-parallel

https://dzone.com/articles/java-8-string-all-combinations-in-parallel

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:
java 1.7 ,string

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}