Skip to content

Instantly share code, notes, and snippets.

@JosePaumard
Last active September 15, 2019 13:23
Show Gist options
  • Save JosePaumard/ba9d255ebb1b68b76639681d510f3c71 to your computer and use it in GitHub Desktop.
Save JosePaumard/ba9d255ebb1b68b76639681d510f3c71 to your computer and use it in GitHub Desktop.
import org.assertj.core.api.Assertions;
import org.eclipse.collections.api.bag.primitive.CharBag;
import org.eclipse.collections.impl.factory.Strings;
import org.junit.Test;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class CountingLetters {
@Test
public void the_quick_brown_fow_jumps_over_the_lazy_dog_with_this_awesome_framework_called_Eclipse_Collections() {
String sentence = "The quick brown fox jumps over the lazy dog.";
CharBag bag =
Strings.asChars(sentence)
.select(Character::isLetter)
.collectChar(Character::toLowerCase)
.toBag();
int sizeDistinct = bag.sizeDistinct();
int size = bag.size();
Assertions.assertThat(sizeDistinct).isEqualTo(26);
Assertions.assertThat(size).isEqualTo(35);
}
@Test
public void the_quick_brown_fow_jumps_over_the_lazy_dog_with_this_with_this_amazing_Stream_and_Collectors_API_V1() {
String sentence = "The quick brown fox jumps over the lazy dog.";
Map<Character, Long> counts = sentence.chars()
.filter(Character::isLetter)
.map(Character::toLowerCase)
.mapToObj(i -> Character.valueOf((char) i))
.collect(Collectors.groupingBy(letter -> letter, Collectors.counting()));
int sizeDistinct = counts.keySet().size();
int size = counts.values().stream().mapToInt(Long::intValue).sum();
Assertions.assertThat(sizeDistinct).isEqualTo(26);
Assertions.assertThat(size).isEqualTo(35);
}
@Test
public void the_quick_brown_fow_jumps_over_the_lazy_dog_with_this_with_this_amazing_Stream_and_Collectors_API_V2() {
String sentence = "The quick brown fox jumps over the lazy dog.";
LetterCollector letterCollector = sentence.chars()
.filter(Character::isLetter)
.mapToObj(Character::toLowerCase)
.reduce(new LetterCollector(), LetterCollector::accumulate, LetterCollector::combine);
int sizeDistinct = letterCollector.numberOfDifferentLetters();
int size = letterCollector.numberOfLetters();
Assertions.assertThat(sizeDistinct).isEqualTo(26);
Assertions.assertThat(size).isEqualTo(35);
}
private class LetterCollector {
private int count = 0;
private Set<Integer> differentLetters = new HashSet<>();
public LetterCollector() {
}
public LetterCollector accumulate(int letter) {
count++;
differentLetters.add(letter);
return this;
}
public LetterCollector combine(LetterCollector other) {
count += other.count;
differentLetters.addAll(other.differentLetters);
return this;
}
public int numberOfDifferentLetters() {
return differentLetters.size();
}
public int numberOfLetters() {
return count;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment