Posted By

borysn on 05/31/13


Tagged

list random character sring


Versions (?)

Create String List With Random Characters And Sort


 / Published in: Java
 

Create a List for a specified number strings with a specified max characters (randomized...1-max). This method uses another snippet which contains initCharacterList(int, int) http://snipplr.com/view/71355/fill-character-list-from-ascii-table-and-sort/

  1. private List<String> initStringList(int maxNumberOfCharacters, int numberOfStrings) {
  2. // init place holder for sorted list
  3. List<String> list = new ArrayList<>();
  4.  
  5. for (int i = 0; i < numberOfStrings; i++) {
  6. // init a mutable string to add characters to
  7. StringBuffer strBuffer = new StringBuffer();
  8.  
  9. // generate random number 1 - numberOfCharacters
  10. int numberOfCharacters = 1 + (int)(Math.random() * ((maxNumberOfCharacters - 1) +1));
  11. // generate random ascii start place between 33 - 100
  12. int asciiStartRand = 33 + (int)(Math.random() * ((100 - 33) + 1));
  13. // going to use initCharacterList(int) to fill strings
  14. for (Character c : initCharacterList(numberOfCharacters, asciiStartRand, 126)) {
  15. // append characters to String
  16. strBuffer.append(c);
  17. }
  18. // convert to String and add to list
  19. list.add(strBuffer.toString());
  20. }
  21.  
  22. // sort list
  23. Collections.sort(list);
  24.  
  25. return list;
  26. }

Report this snippet  

You need to login to post a comment.