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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

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 }}