fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10.  
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. int reps = 100000;
  14. Map<String, String> map = null;
  15. //warmup
  16. for (int i = 0; i < reps; i++){
  17. map = simple();
  18. }
  19. long start = System.currentTimeMillis();
  20. for (int i = 0; i < reps; i++){
  21. map = simple();
  22. }
  23. long stop = System.currentTimeMillis();
  24. System.out.println(stop - start);
  25. //warmup
  26. for (int i = 0; i < reps; i++){
  27. map = convoluted();
  28. }
  29. start = System.currentTimeMillis();
  30. for (int i = 0; i < reps; i++){
  31. map = convoluted();
  32. }
  33. stop = System.currentTimeMillis();
  34. System.out.println(stop - start);
  35.  
  36. System.out.println(map);
  37. }
  38.  
  39. private static Map<String, String> convoluted() {
  40. String test = "pet:cat::car:honda::location:Japan::food:sushi";
  41. boolean stateiskey = true;
  42.  
  43. Map<String, String> map = new HashMap<>();
  44. int keystart = 0;
  45. int keyend = 0;
  46. int valuestart = 0;
  47. int valueend = 0;
  48.  
  49. for(int i = 0; i < test.length(); i++){
  50. char nextchar = test.charAt(i);
  51. if (stateiskey) {
  52. if (nextchar == ':') {
  53. keyend = i;
  54. stateiskey = false;
  55. valuestart = i + 1;
  56. }
  57. } else {
  58. if (i == test.length() - 1 || (nextchar == ':' && test.charAt(i + 1) == ':')) {
  59. valueend = i;
  60. if (i + 1 == test.length()) valueend += 1; //compensate one for the end of the string
  61. String key = test.substring(keystart, keyend);
  62. String value = test.substring(valuestart, valueend);
  63. keystart = i + 2;
  64. map.put(key, value);
  65. i++;
  66. stateiskey = true;
  67. }
  68. }
  69. }
  70. return map;
  71. }
  72.  
  73. private static Map<String, String> simple(){
  74. Map<String, String> map = new HashMap<String, String>();
  75. String test = "pet:cat::car:honda::location:Japan::food:sushi";
  76. String[] test1 = test.split("::");
  77.  
  78. for (String s : test1) {
  79. String[] t = s.split(":");
  80. map.put(t[0], t[1]);
  81. }
  82. return map;
  83. }
  84. }
Success #stdin #stdout 1.19s 320640KB
stdin
Standard input is empty
stdout
415
99
{car=honda, location=Japan, pet=cat, food=sushi}