Skip to content

Instantly share code, notes, and snippets.

@apangin
Created June 8, 2021 12:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apangin/d4806c824f95e3e49445564bff006d56 to your computer and use it in GitHub Desktop.
Save apangin/d4806c824f95e3e49445564bff006d56 to your computer and use it in GitHub Desktop.
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
// See https://twitter.com/tagir_valeev/status/1402089474805354499
public class StringBuilderHash {
public static void main(String[] args) {
List<StringBuilder> list = IntStream.range(0, 10_000_000)
.mapToObj(i -> new StringBuilder(0))
.filter(s -> ((s.hashCode() ^ s.hashCode() >>> 16) & 0xfff) == 0)
.sorted(Comparator.comparingInt(Object::hashCode))
.collect(Collectors.toList());
StringBuilder sb = list.remove(IntStream.range(1, list.size())
.filter(i -> list.get(i).hashCode() == list.get(i - 1).hashCode())
.findFirst()
.orElseThrow());
Set<StringBuilder> set = new HashSet<>(list);
set.add(sb);
System.out.println(set.contains(sb));
sb.append("oops");
System.out.println(set.contains(sb));
}
}
@shutuper
Copy link

shutuper commented Apr 4, 2023

with range(0, 2_350_000) and limit(150) even faster :) (but it's a genius solution)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment