Example usage for com.google.common.collect Sets filter

List of usage examples for com.google.common.collect Sets filter

Introduction

In this page you can find the example usage for com.google.common.collect Sets filter.

Prototype

@GwtIncompatible("NavigableSet")
@SuppressWarnings("unchecked")
@CheckReturnValue
public static <E> NavigableSet<E> filter(NavigableSet<E> unfiltered, Predicate<? super E> predicate) 

Source Link

Document

Returns the elements of a NavigableSet , unfiltered , that satisfy a predicate.

Usage

From source file:eu.interedition.text.event.AnnotationEventSource.java

public void listen(final AnnotationEventListener listener, final int pageSize, final Text text,
        final Criterion criterion, final Set<Name> dataSet) throws IOException {
    textRepository.read(text, new TextConsumer() {

        public void read(Reader content, long contentLength) throws IOException {
            final SortedMap<Long, Set<Annotation>> starts = Maps.newTreeMap();
            final SortedMap<Long, Set<Annotation>> ends = Maps.newTreeMap();

            long offset = 0;
            long next = 0;
            long pageEnd = 0;

            listener.start();/*w  w w  .  java2s  .c o m*/

            final Set<Annotation> annotationData = Sets.newHashSet();
            while (true) {
                if ((offset % pageSize) == 0) {
                    pageEnd = Math.min(offset + pageSize, contentLength);
                    final Range pageRange = new Range(offset, pageEnd);
                    final Iterable<Annotation> pageAnnotations = annotationRepository
                            .find(and(criterion, text(text), rangeOverlap(pageRange)), dataSet);
                    for (Annotation a : pageAnnotations) {
                        final long start = a.getRange().getStart();
                        final long end = a.getRange().getEnd();
                        if (start >= offset) {
                            Set<Annotation> starting = starts.get(start);
                            if (starting == null) {
                                starts.put(start, starting = Sets.newHashSet());
                            }
                            starting.add(a);
                            annotationData.add(a);
                        }
                        if (end <= pageEnd) {
                            Set<Annotation> ending = ends.get(end);
                            if (ending == null) {
                                ends.put(end, ending = Sets.newHashSet());
                            }
                            ending.add(a);
                            annotationData.add(a);
                        }
                    }

                    next = Math.min(starts.isEmpty() ? contentLength : starts.firstKey(),
                            ends.isEmpty() ? contentLength : ends.firstKey());
                }

                if (offset == next) {
                    final Set<Annotation> startEvents = (!starts.isEmpty() && offset == starts.firstKey()
                            ? starts.remove(starts.firstKey())
                            : Sets.<Annotation>newHashSet());
                    final Set<Annotation> endEvents = (!ends.isEmpty() && offset == ends.firstKey()
                            ? ends.remove(ends.firstKey())
                            : Sets.<Annotation>newHashSet());

                    final Set<Annotation> terminating = Sets.filter(endEvents, Predicates.not(EMPTY));
                    if (!terminating.isEmpty())
                        listener.end(offset, filter(annotationData, terminating, true));

                    final Set<Annotation> empty = Sets.filter(startEvents, EMPTY);
                    if (!empty.isEmpty())
                        listener.empty(offset, filter(annotationData, empty, true));

                    final Set<Annotation> starting = Sets.filter(startEvents, Predicates.not(EMPTY));
                    if (!starting.isEmpty())
                        listener.start(offset, filter(annotationData, starting, false));

                    next = Math.min(starts.isEmpty() ? contentLength : starts.firstKey(),
                            ends.isEmpty() ? contentLength : ends.firstKey());
                }

                if (offset == contentLength) {
                    break;
                }

                final long readTo = Math.min(pageEnd, next);
                if (offset < readTo) {
                    final char[] currentText = new char[(int) (readTo - offset)];
                    int read = content.read(currentText);
                    if (read > 0) {
                        listener.text(new Range(offset, offset + read), new String(currentText, 0, read));
                        offset += read;
                    }
                }
            }

            listener.end();
        }
    });
}

From source file:org.spka.cursus.test.AbstractSPKASeries.java

/**
 * Get all the pilots in a Scotland series (only up to and including the specified event)
 *//*from w  ww.  ja va 2  s  .  c om*/
public Set<Pilot> getSeriesResultsPilots(final Series series, final Event event) {
    return Sets.filter(series.getPilots(), new Predicate<Pilot>() {
        @Override
        public boolean apply(@Nonnull Pilot pilot) {
            for (Race race : pilot.getRaces().keySet()) {
                if (race.getEvent().compareTo(event) <= 0) {
                    return SERIES_COUNTRIES.contains(pilot.getCountry());
                }
            }

            for (Event event_ : pilot.getEvents()) {
                if (event_.compareTo(event) <= 0) {
                    return SERIES_COUNTRIES.contains(pilot.getCountry());
                }
            }

            return false;
        }
    });
}

From source file:com.censoredsoftware.infractions.bukkit.origin.Origin.java

/**
 * Set of Dossiers with data from this Origin.
 *
 * @return Dossiers.//from w  w  w  .j a  va  2 s .c o  m
 */
public Set<Dossier> getContributedDossiers() {
    final Origin origin = this;
    return Sets.filter(Infractions.allDossiers(), new Predicate<Dossier>() {
        @Override
        public boolean apply(Dossier dossier) {
            return Iterables.any(dossier.getInfractions(), new Predicate<Infraction>() {
                @Override
                public boolean apply(Infraction infraction) {
                    return origin.equals(infraction.getOrigin())
                            || Iterables.any(infraction.getEvidence(), new Predicate<Evidence>() {
                                @Override
                                public boolean apply(Evidence evidence) {
                                    return origin.equals(evidence.getOrigin());
                                }
                            });
                }
            });
        }
    });
}

From source file:com.streamsets.datacollector.record.HeaderImpl.java

@Override
public Set<String> getAttributeNames() {
    return ImmutableSet.copyOf(Sets.filter(map.keySet(), this));
}

From source file:com.censoredsoftware.infractions.bukkit.legacy.compat.LegacyDatabase.java

@SuppressWarnings("unchecked")
@Override//  w  ww  . java2  s . c  o  m
public Set<CompleteDossier> getCompleteDossiers(final InetAddress address) {
    return (Set<CompleteDossier>) (Set) Sets.filter(allDossiers(), new Predicate<Dossier>() {
        @Override
        public boolean apply(Dossier dossier) {
            return dossier instanceof CompleteDossier
                    && ((CompleteDossier) dossier).getAssociatedIPAddresses().contains(address);
        }
    });
}

From source file:com.isotrol.impe3.pms.core.obj.ConnectorsGraph.java

/**
 * Returns the iteration order. WARNING: destructive operation.
 * @return The iteration order.//from  ww  w .  j a v a 2s.c  o m
 */
Iterable<ConnectorObject> getInstantiationOrder() {
    final Predicate<ConnectorObject> inDegree = new Predicate<ConnectorObject>() {
        public boolean apply(ConnectorObject input) {
            return graph.inDegreeOf(input) == 0;
        }
    };
    final Set<ConnectorObject> v = graph.vertexSet();
    final List<ConnectorObject> ordered = Lists.newArrayListWithCapacity(v.size());
    while (!v.isEmpty()) {
        final Set<ConnectorObject> zero = Sets.newHashSet(Sets.filter(v, inDegree));
        for (ConnectorObject c : zero) {
            ordered.add(c);
            graph.removeVertex(c);
        }
    }
    return ordered;
}

From source file:com.facebook.buck.core.util.graph.MutableDirectedGraph.java

public ImmutableSet<ImmutableSet<T>> findCycles() {
    Set<Set<T>> cycles = Sets.filter(findStronglyConnectedComponents(),
            stronglyConnectedComponent -> stronglyConnectedComponent.size() > 1);
    Iterable<ImmutableSet<T>> immutableCycles = Iterables.transform(cycles, ImmutableSet::copyOf);

    // Tarjan's algorithm (as pseudo-coded on Wikipedia) does not appear to account for single-node
    // cycles. Therefore, we must check for them exclusively.
    ImmutableSet.Builder<ImmutableSet<T>> builder = ImmutableSet.builder();
    builder.addAll(immutableCycles);//from ww w  . j  av a2s.c  om
    for (T node : nodes) {
        if (containsEdge(node, node)) {
            builder.add(ImmutableSet.of(node));
        }
    }
    return builder.build();
}

From source file:eu.interedition.text.query.QueryCriterion.java

public void listen(Session session, final Text text, final int pageSize, final AnnotationListener listener)
        throws IOException {
    final long contentLength = text.getLength();
    Reader contentStream = null;//  www.  ja v a  2  s .c om
    try {
        contentStream = text.read().getInput();
        final SortedMap<Long, Set<Annotation>> starts = Maps.newTreeMap();
        final SortedMap<Long, Set<Annotation>> ends = Maps.newTreeMap();

        long offset = 0;
        long next = 0;
        long pageEnd = 0;

        listener.start(contentLength);

        final Set<Annotation> annotationData = Sets.newHashSet();
        while (true) {
            if ((offset % pageSize) == 0) {
                pageEnd = Math.min(offset + pageSize, contentLength);
                final TextRange pageRange = new TextRange(offset, pageEnd);
                final Iterable<Annotation> pageAnnotations = and(this, text(text), rangeOverlap(pageRange))
                        .iterate(session);
                for (Annotation a : pageAnnotations) {
                    for (TextTarget target : a.getTargets()) {
                        if (!text.equals(target.getText())) {
                            continue;
                        }
                        final long start = target.getStart();
                        final long end = target.getEnd();
                        if (start >= offset) {
                            Set<Annotation> starting = starts.get(start);
                            if (starting == null) {
                                starts.put(start, starting = Sets.newHashSet());
                            }
                            starting.add(a);
                            annotationData.add(a);
                        }
                        if (end <= pageEnd) {
                            Set<Annotation> ending = ends.get(end);
                            if (ending == null) {
                                ends.put(end, ending = Sets.newHashSet());
                            }
                            ending.add(a);
                            annotationData.add(a);
                        }
                    }
                }

                next = Math.min(starts.isEmpty() ? contentLength : starts.firstKey(),
                        ends.isEmpty() ? contentLength : ends.firstKey());
            }

            if (offset == next) {
                final Set<Annotation> startEvents = (!starts.isEmpty() && offset == starts.firstKey()
                        ? starts.remove(starts.firstKey())
                        : Sets.<Annotation>newHashSet());
                final Set<Annotation> endEvents = (!ends.isEmpty() && offset == ends.firstKey()
                        ? ends.remove(ends.firstKey())
                        : Sets.<Annotation>newHashSet());

                final Set<Annotation> emptyEvents = Sets.newHashSet(Sets.filter(endEvents, emptyIn(text)));
                endEvents.removeAll(emptyEvents);

                if (!endEvents.isEmpty())
                    listener.end(offset, filter(annotationData, endEvents, true));
                if (!startEvents.isEmpty())
                    listener.start(offset, filter(annotationData, startEvents, false));
                if (!emptyEvents.isEmpty())
                    listener.end(offset, filter(annotationData, emptyEvents, true));

                next = Math.min(starts.isEmpty() ? contentLength : starts.firstKey(),
                        ends.isEmpty() ? contentLength : ends.firstKey());
            }

            if (offset == contentLength) {
                break;
            }

            final long readTo = Math.min(pageEnd, next);
            if (offset < readTo) {
                final char[] currentText = new char[(int) (readTo - offset)];
                int read = contentStream.read(currentText);
                if (read > 0) {
                    listener.text(new TextRange(offset, offset + read), new String(currentText, 0, read));
                    offset += read;
                }
            }
        }

        listener.end();
    } finally {
        Closeables.close(contentStream, false);
    }
}

From source file:org.gradle.plugins.ide.idea.IdeaPlugin.java

private void registerImlArtifacts() {
    Set<Project> projectsWithIml = Sets.filter(project.getRootProject().getAllprojects(),
            new Predicate<Project>() {
                @Override/*from   ww  w.j a  va2  s.  c o m*/
                public boolean apply(Project project) {
                    return project.getPlugins().hasPlugin(IdeaPlugin.class);
                }
            });
    for (Project project : projectsWithIml) {
        ProjectLocalComponentProvider projectComponentProvider = ((ProjectInternal) project).getServices()
                .get(ProjectLocalComponentProvider.class);
        ProjectComponentIdentifier projectId = newProjectId(project);
        projectComponentProvider.registerAdditionalArtifact(projectId, createImlArtifact(projectId, project));
    }
}

From source file:com.android.tools.idea.gradle.structure.editors.ModuleDependenciesPanel.java

public ModuleDependenciesPanel(@NotNull Project project, @NotNull String modulePath) {
    super(new BorderLayout());

    myModulePath = modulePath;/*from   w  ww .  j  a  v a  2  s  . c  o  m*/
    myProject = project;
    myModel = new ModuleDependenciesTableModel();
    myGradleSettingsFile = GradleSettingsFile.get(myProject);

    Module module = GradleUtil.findModuleByGradlePath(myProject, modulePath);
    myGradleBuildFile = module != null ? GradleBuildFile.get(module) : null;
    if (myGradleBuildFile != null) {
        List<BuildFileStatement> dependencies = myGradleBuildFile.getDependencies();
        for (BuildFileStatement dependency : dependencies) {
            myModel.addItem(new ModuleDependenciesTableItem(dependency));
        }
    } else {
        LOG.warn("Unable to find Gradle build file for module " + myModulePath);
    }
    myModel.resetModified();

    myEntryTable = new JBTable(myModel);
    TableRowSorter<ModuleDependenciesTableModel> sorter = new TableRowSorter<>(myModel);
    sorter.setRowFilter(myModel.getFilter());
    myEntryTable.setRowSorter(sorter);
    myEntryTable.setShowGrid(false);
    myEntryTable.setDragEnabled(false);
    myEntryTable.setIntercellSpacing(new Dimension(0, 0));

    myEntryTable.setDefaultRenderer(ModuleDependenciesTableItem.class, new TableItemRenderer());

    if (myGradleBuildFile == null) {
        return;
    }
    final boolean isAndroid = myGradleBuildFile.hasAndroidPlugin();
    List<Dependency.Scope> scopes = Lists.newArrayList(Sets.filter(EnumSet.allOf(Dependency.Scope.class),
            input -> isAndroid ? input.isAndroidScope() : input.isJavaScope()));
    ComboBoxModel<Dependency.Scope> boxModel = new CollectionComboBoxModel<>(scopes, null);
    JComboBox<Dependency.Scope> scopeEditor = new ComboBox<>(boxModel);
    myEntryTable.setDefaultEditor(Dependency.Scope.class, new DefaultCellEditor(scopeEditor));
    myEntryTable.setDefaultRenderer(Dependency.Scope.class,
            new ComboBoxTableRenderer<Dependency.Scope>(Dependency.Scope.values()) {
                @Override
                protected String getTextFor(@NotNull final Dependency.Scope value) {
                    return value.getDisplayName();
                }
            });

    myEntryTable.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    new SpeedSearchBase<JBTable>(myEntryTable) {
        @Override
        public int getSelectedIndex() {
            return myEntryTable.getSelectedRow();
        }

        @Override
        protected int convertIndexToModel(int viewIndex) {
            return myEntryTable.convertRowIndexToModel(viewIndex);
        }

        @Override
        @NotNull
        public Object[] getAllElements() {
            return myModel.getItems().toArray();
        }

        @Override
        @NotNull
        public String getElementText(Object element) {
            return getCellAppearance((ModuleDependenciesTableItem) element).getText();
        }

        @Override
        public void selectElement(@NotNull Object element, @NotNull String selectedText) {
            final int count = myModel.getRowCount();
            for (int row = 0; row < count; row++) {
                if (element.equals(myModel.getItemAt(row))) {
                    final int viewRow = myEntryTable.convertRowIndexToView(row);
                    myEntryTable.getSelectionModel().setSelectionInterval(viewRow, viewRow);
                    TableUtil.scrollSelectionToVisible(myEntryTable);
                    break;
                }
            }
        }
    };

    TableColumn column = myEntryTable.getTableHeader().getColumnModel()
            .getColumn(ModuleDependenciesTableModel.SCOPE_COLUMN);
    column.setResizable(false);
    column.setMaxWidth(SCOPE_COLUMN_WIDTH);
    column.setMinWidth(SCOPE_COLUMN_WIDTH);

    add(createTableWithButtons(), BorderLayout.CENTER);

    if (myEntryTable.getRowCount() > 0) {
        myEntryTable.getSelectionModel().setSelectionInterval(0, 0);
    }

    DefaultActionGroup actionGroup = new DefaultActionGroup();
    actionGroup.add(myRemoveButton);
    PopupHandler.installPopupHandler(myEntryTable, actionGroup, ActionPlaces.UNKNOWN,
            ActionManager.getInstance());
}