Created
November 23, 2019 10:36
-
-
Save cyrexcyborg/793be1fe082093d002e25bdd52017ec2 to your computer and use it in GitHub Desktop.
A Java 8 approach to do strings join
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.jupiter.api.Assertions; | |
import org.junit.jupiter.api.Test; | |
import java.util.*; | |
import java.util.concurrent.atomic.AtomicInteger; | |
/* | |
* Test for joining collection of String's into one | |
* like ["a", "aaa", "bbbb", "Dda"] to "a,aaa,bbbb,Dda" | |
* | |
* */ | |
class JoinStringsTest { | |
@Test | |
void happy() { | |
Collection<String> collection = new ArrayList<>(); | |
String delim = ","; | |
Assertions.assertEquals(joinString(collection, delim), Optional.of("")); | |
} | |
@Test | |
void nullCheckArgs() { | |
Collection<String> collection = new ArrayList<>(); | |
String delim = ","; | |
Assertions.assertEquals(joinString(collection, delim), Optional.of("")); | |
} | |
@Test | |
void onlyOneElement() { | |
Collection<String> collection = new ArrayList<>(); | |
collection.add("a"); | |
String delim = ","; | |
Assertions.assertEquals(joinString(collection, delim), Optional.of("a")); | |
} | |
@Test | |
void twoElements() { | |
Collection<String> collection = new ArrayList<>(); | |
collection.add("a"); | |
collection.add("aa"); | |
String delim = ","; | |
Assertions.assertEquals(joinString(collection, delim), Optional.of("a,aa")); | |
} | |
private static Optional<String> joinString(Iterable<String> collection, String delim) { | |
Optional<String> result; | |
if (collection == null || delim == null || !collection.iterator().hasNext()) { | |
result = Optional.of(""); | |
} else { | |
AtomicInteger finalCount = new AtomicInteger(0); | |
Iterator<String> strings = collection.iterator(); | |
collection.forEach(s -> finalCount.getAndIncrement()); | |
if (finalCount.get() == 1) { | |
result = Optional.of(strings.next()); | |
} else { | |
StringBuilder buffer = new StringBuilder(); | |
while (strings.hasNext()) { | |
buffer.append(strings.next()).append(delim); | |
} | |
result = Optional.of(buffer.deleteCharAt(buffer.length() - 1).toString()); | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment