Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java String Permutations Code Snippet

DZone's Guide to

Java String Permutations Code Snippet

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

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

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

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java 1.7 ,string

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}