Skip to content

Instantly share code, notes, and snippets.

@runeflobakk
Last active February 7, 2021 01:28
Show Gist options
  • Save runeflobakk/7439934c0084fe372636e18eebe969e0 to your computer and use it in GitHub Desktop.
Save runeflobakk/7439934c0084fe372636e18eebe969e0 to your computer and use it in GitHub Desktop.
Terrible oh-so-functional Java

Tried to make an as convoluted as I possibly can "functional" solution in Java to this problem: https://twitter.com/Al_Grigor/status/1357028887209902088

I would not have made the 25 minute limit and fail to get the job, and on my way home would probably also beat myself up for not just using a damn for-loop.

Fun exercise none the less.

record Count<T>(T item, int count) {
List<Count<T>> sumIf(BiPredicate<? super T, ? super T> shouldSum, Count<T> other) {
return shouldSum.test(item, other.item) ? List.of(new Count<>(item, count + other.count)) : List.of(this, other);
}
@Override
public String toString() {
return "(\"" + item + "\"," + count + ")";
}
}
var equalConsecutiveCharsCounts =
"aaaabbbcca".chars()
.mapToObj(c -> new Count<>((char) c, 1))
.collect(LinkedList<Count<Character>>::new,
(counts, count) -> Optional.ofNullable(counts.pollLast())
.map(lastCount -> lastCount.sumIf(Objects::equals, count))
.ifPresentOrElse(counts::addAll, () -> counts.add(count)),
List<Count<Character>>::addAll);
System.out.println(equalConsecutiveCharsCounts); // [("a",4), ("b",3), ("c",2), ("a",1)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment