fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.*;
  5. import static java.util.stream.Collectors.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone {
  10. public static void main (String[] args) throws Exception {
  11. // warm up + JIT
  12. for (int i = 10; i < 999; i++)
  13. time(i);
  14. Thread.yield();
  15. Thread.sleep(200);
  16. for (int i = 10; i < 100001; i *= 10)
  17. System.out.format("Word length %d had time of %d per letter\n", i, time(i) / i);
  18. }
  19.  
  20. static long time(int length) {
  21. long start = System.nanoTime();
  22. for (int i = 0; i < 10; i++)
  23. charFreq(random(length)).equals(charFreq(random(length)));
  24. return System.nanoTime() - start;
  25. }
  26.  
  27. static String random(int length) {
  28. return IntStream.generate(() -> 'a' + (int)Math.sqrt(Math.random() * 26 * 26))
  29. .limit(length)
  30. .mapToObj(i -> (char)i + "")
  31. .collect(Collectors.joining(""));
  32. }
  33.  
  34. static boolean anagram(String strA, String strB) {
  35. return charFreq(strA).equals(charFreq(strB));
  36. }
  37.  
  38. static Map<Integer, Long> charFreq(String str) {
  39. return str.chars().boxed().collect(groupingBy(i -> i, counting()));
  40. }
  41.  
  42. }
Success #stdin #stdout 2.16s 711680KB
stdin
Standard input is empty
stdout
Word length 10 had time of 6227 per letter
Word length 100 had time of 3444 per letter
Word length 1000 had time of 3214 per letter
Word length 10000 had time of 3271 per letter
Word length 100000 had time of 3299 per letter