Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.regex.Pattern;
- public class CollectionExample {
- public static void main(String[] args) {
- new CollectionExample().run();
- }
- private void run() {
- List<String> sortedNewsgroupNames = getGroupNames();
- for (String name: sortedNewsgroupNames) {
- System.out.println("All: " + name);
- }
- List<String> filterdGroupNames = filter(new String[] {"de.alt.foo"}, "", getGroupNames());
- for (String name: filterdGroupNames) {
- System.out.println("Filtered: " + name);
- }
- }
- private List<String> getGroupNames() {
- String[] loadedNewsgroupNames = loadGroupNames();
- List<String> sortedNewsgroupNames = new LinkedList<String>(new HashSet<String>(Arrays.asList(loadedNewsgroupNames)));
- Collections.sort(sortedNewsgroupNames);
- return sortedNewsgroupNames;
- }
- private String[] loadGroupNames() {
- return new String[] {"xyz", "de.alt.foo", "de.alt.bar", "comp.alt.science"};
- }
- private List<String> filter(final String[] selectedGroups, final String filterInput, final List<String> sortedGroupNames) {
- StringBuilder selectedGroupsSB = new StringBuilder("^(");
- for (String group: selectedGroups) {
- selectedGroupsSB.append(group).append('|');
- }
- Pattern selectedGroupsPattern = null;
- if (0 < selectedGroups.length) {
- selectedGroupsSB.deleteCharAt(selectedGroupsSB.length() - 1);
- selectedGroupsSB.append(")$");
- selectedGroupsPattern = Pattern.compile(selectedGroupsSB.toString());
- }
- Pattern filterInputPattern = null;
- if (null != filterInput && !filterInput.isEmpty()) {
- filterInputPattern = Pattern.compile(filterInput);
- }
- List<String> visibleGroupNames = new LinkedList<String>();
- for (String group: sortedGroupNames) {
- if (null != selectedGroupsPattern) {
- if (!selectedGroupsPattern.matcher(group).matches()) {
- continue;
- }
- }
- if (null != filterInputPattern) {
- if (!filterInputPattern.matcher(group).find()) {
- continue;
- }
- }
- visibleGroupNames.add(group);
- }
- return visibleGroupNames;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement