Advertisement
Guest User

Untitled

a guest
Jun 30th, 2015
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Collections;
  3. import java.util.HashSet;
  4. import java.util.LinkedList;
  5. import java.util.List;
  6. import java.util.regex.Pattern;
  7.  
  8. public class CollectionExample {
  9. public static void main(String[] args) {
  10. new CollectionExample().run();
  11. }
  12.  
  13. private void run() {
  14. List<String> sortedNewsgroupNames = getGroupNames();
  15. for (String name: sortedNewsgroupNames) {
  16. System.out.println("All: " + name);
  17. }
  18.  
  19. List<String> filterdGroupNames = filter(new String[] {"de.alt.foo"}, "", getGroupNames());
  20. for (String name: filterdGroupNames) {
  21. System.out.println("Filtered: " + name);
  22. }
  23. }
  24.  
  25. private List<String> getGroupNames() {
  26. String[] loadedNewsgroupNames = loadGroupNames();
  27. List<String> sortedNewsgroupNames = new LinkedList<String>(new HashSet<String>(Arrays.asList(loadedNewsgroupNames)));
  28. Collections.sort(sortedNewsgroupNames);
  29. return sortedNewsgroupNames;
  30. }
  31.  
  32. private String[] loadGroupNames() {
  33. return new String[] {"xyz", "de.alt.foo", "de.alt.bar", "comp.alt.science"};
  34. }
  35.  
  36. private List<String> filter(final String[] selectedGroups, final String filterInput, final List<String> sortedGroupNames) {
  37.  
  38. StringBuilder selectedGroupsSB = new StringBuilder("^(");
  39. for (String group: selectedGroups) {
  40. selectedGroupsSB.append(group).append('|');
  41. }
  42. Pattern selectedGroupsPattern = null;
  43. if (0 < selectedGroups.length) {
  44. selectedGroupsSB.deleteCharAt(selectedGroupsSB.length() - 1);
  45. selectedGroupsSB.append(")$");
  46. selectedGroupsPattern = Pattern.compile(selectedGroupsSB.toString());
  47. }
  48. Pattern filterInputPattern = null;
  49. if (null != filterInput && !filterInput.isEmpty()) {
  50. filterInputPattern = Pattern.compile(filterInput);
  51. }
  52.  
  53. List<String> visibleGroupNames = new LinkedList<String>();
  54. for (String group: sortedGroupNames) {
  55. if (null != selectedGroupsPattern) {
  56. if (!selectedGroupsPattern.matcher(group).matches()) {
  57. continue;
  58. }
  59. }
  60. if (null != filterInputPattern) {
  61. if (!filterInputPattern.matcher(group).find()) {
  62. continue;
  63. }
  64. }
  65. visibleGroupNames.add(group);
  66. }
  67.  
  68. return visibleGroupNames;
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement