Java Code Examples for com.google.common.collect.Iterators#filter()

The following examples show how to use com.google.common.collect.Iterators#filter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DirectedNodeAdjacencies.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public Set<N> successors() {
  // Don't simply use Sets.filter() or we'll end up with O(N) instead of O(1) size().
  return new AbstractSet<N>() {
    @Override
    public Iterator<N> iterator() {
      return Iterators.filter(adjacentNodes().iterator(), new Predicate<N>() {
        @Override
        public boolean apply(N node) {
          return isSuccessor(node);
        }
      });
    }

    @Override
    public int size() {
      return successorCount;
    }

    @Override
    public boolean contains(Object o) {
      return isSuccessor(o);
    }
  };
}
 
Example 2
Source File: ParseResult.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Iterable<INode> getSyntaxErrors() {
	if (rootNode == null || !hasSyntaxErrors())
		return Collections.emptyList();
	return new Iterable<INode>() {
		@Override
		@SuppressWarnings("unchecked")
		public Iterator<INode> iterator() {
			Iterator<? extends INode> result = Iterators.filter(((CompositeNode) rootNode).basicIterator(),
					new Predicate<AbstractNode>() {
				@Override
				public boolean apply(AbstractNode input) {
					return input.getSyntaxErrorMessage() != null;
				}
			});
			return (Iterator<INode>) result;
		}
	};
}
 
Example 3
Source File: StatisticsRowIterator.java    From geowave with Apache License 2.0 6 votes vote down vote up
public StatisticsRowIterator(
    final CloseableIterator<GeoWaveMetadata> resultIterator,
    final String... authorizations) {
  if ((authorizations != null) && (authorizations.length > 0)) {
    final Set<String> authorizationsSet = new HashSet<>(Arrays.asList(authorizations));
    it =
        new CloseableIteratorWrapper<>(resultIterator, Iterators.filter(resultIterator, input -> {
          String visibility = "";
          if (input.getVisibility() != null) {
            visibility = StringUtils.stringFromBinary(input.getVisibility());
          }
          return VisibilityExpression.evaluate(visibility, authorizationsSet);
        }));
  } else {
    it =
        new CloseableIteratorWrapper<>(
            resultIterator,
            // we don't have any authorizations
            // so this row cannot have any
            // visibilities
            Iterators.filter(
                resultIterator,
                input -> (input.getVisibility() == null) || (input.getVisibility().length == 0)));
  }
}
 
Example 4
Source File: Mappings.java    From ReactionDecoder with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Filter the mappings for those which cover a unique set of atoms in the
 * target. The unique atom mappings are a subset of the unique bond matches.
 *
 * @return fluent-api instance
 * @see #uniqueBonds()
 */
public Mappings uniqueAtoms() {
    // we need the unique predicate to be reset for each new iterator -
    // otherwise multiple iterations are always filtered (seen before)
    return new Mappings(query, target, new Iterable<int[]>() {

        @Override
        public Iterator<int[]> iterator() {
            return Iterators.filter(iterable.iterator(), new UniqueAtomMatches());
        }
    });
}
 
Example 5
Source File: BlockImpl.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
@Override
public Iterator<Statement> getAllStatements() {
	final Predicate<EObject> _function = new Predicate<EObject>() {
		public boolean apply(final EObject it) {
			return (!((it instanceof Expression) || (it instanceof FunctionDefinition)));
		}
	};
	return Iterators.<Statement>filter(EcoreUtilN4.getAllContentsFiltered(this, _function), Statement.class);
}
 
Example 6
Source File: AbstractScope.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Iterator<IEObjectDescription> iterator() {
	if (parentElements == null) {
		parentElements = provider.get();
	}
	Iterator<IEObjectDescription> parentIterator = parentElements.iterator();
	Iterator<IEObjectDescription> filteredIterator = Iterators.filter(parentIterator, this);
	return filteredIterator;
}
 
Example 7
Source File: DirectedNodeAdjacencies.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Set<N> predecessors() {
  // Don't simply use Sets.filter() or we'll end up with O(N) instead of O(1) size().
  return new AbstractSet<N>() {
    @Override
    public Iterator<N> iterator() {
      return Iterators.filter(
        adjacentNodes().iterator(),
        new Predicate<N>() {
          @Override
          public boolean apply(N node) {
            return isPredecessor(node);
          }
        });
    }

    @Override
    public int size() {
      return predecessorCount;
    }

    @Override
    public boolean contains(Object o) {
      return isPredecessor(o);
    }
  };
}
 
Example 8
Source File: MySQL5PlayerEffectsDAO.java    From aion-germany with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void storePlayerEffects(final Player player) {
	deletePlayerEffects(player);

	Iterator<Effect> iterator = player.getEffectController().iterator();
	iterator = Iterators.filter(iterator, insertableEffectsPredicate);

	if (!iterator.hasNext()) {
		return;
	}

	Connection con = null;
	PreparedStatement ps = null;
	try {
		con = DatabaseFactory.getConnection();
		con.setAutoCommit(false);
		ps = con.prepareStatement(INSERT_QUERY);

		while (iterator.hasNext()) {
			Effect effect = iterator.next();
			ps.setInt(1, player.getObjectId());
			ps.setInt(2, effect.getSkillId());
			ps.setInt(3, effect.getSkillLevel());
			ps.setInt(4, effect.getRemainingTime());
			ps.setLong(5, effect.getEndTime());
			ps.addBatch();
		}

		ps.executeBatch();
		con.commit();
	}
	catch (SQLException e) {
		log.error("Exception while saving effects of player " + player.getObjectId(), e);
	}
	finally {
		DatabaseFactory.close(ps, con);
	}
}
 
Example 9
Source File: CassandraEmbeddedKeyColumnValueStore.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
private Iterator<Row> getRowsIterator(List<Row> rows) {
    if (rows == null)
        return null;

    return Iterators.filter(rows.iterator(), new Predicate<Row>() {
        @Override
        public boolean apply(@Nullable Row row) {
            // The hasOnlyTombstones(x) call below ultimately calls Column.isMarkedForDelete(x)
            return !(row == null || row.cf == null || row.cf.isMarkedForDelete() || row.cf.hasOnlyTombstones(nowMillis));
        }
    });
}
 
Example 10
Source File: IndexMaintainer.java    From phoenix with Apache License 2.0 5 votes vote down vote up
public static Iterator<PTable> enabledGlobalIndexIterator(Iterator<PTable> indexes) {
    return Iterators.filter(indexes, new Predicate<PTable>() {
        @Override
        public boolean apply(PTable index) {
            return !PIndexState.DISABLE.equals(index.getIndexState()) && !index.getIndexType().equals(IndexType.LOCAL);
        }
    });
}
 
Example 11
Source File: ColumnCondition.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
protected Iterator<Cell> collectionColumns(CellName collection, ColumnFamily cf, final long now)
{
    // We are testing for collection equality, so we need to have the expected values *and* only those.
    ColumnSlice[] collectionSlice = new ColumnSlice[]{ collection.slice() };
    // Filter live columns, this makes things simpler afterwards
    return Iterators.filter(cf.iterator(collectionSlice), new Predicate<Cell>()
    {
        public boolean apply(Cell c)
        {
            // we only care about live columns
            return c.isLive(now);
        }
    });
}
 
Example 12
Source File: AbstractNode.java    From xtext-core with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Iterable<ILeafNode> getLeafNodes() {
	return new Iterable<ILeafNode>() {
		@Override
		public Iterator<ILeafNode> iterator() {
			return Iterators.filter(basicIterator(), ILeafNode.class);
		}
	};
}
 
Example 13
Source File: BaseDataStore.java    From geowave with Apache License 2.0 4 votes vote down vote up
protected <R> CloseableIterator<InternalDataStatistics<?, R, ?>> internalQueryStatistics(
    final StatisticsQuery<R> query) {
  // sanity check, although using the builders should disallow this type
  // of query
  if ((query.getStatsType() == null)
      && (query.getExtendedId() != null)
      && (query.getExtendedId().length() > 0)) {
    LOGGER.error(
        "Cannot query by extended ID '"
            + query.getExtendedId()
            + "' if statistic type is not provided");
    return new CloseableIterator.Empty<>();
  }
  CloseableIterator<InternalDataStatistics<?, R, ?>> it = null;
  if ((query.getTypeName() != null) && (query.getTypeName().length() > 0)) {
    final Short adapterId = internalAdapterStore.getAdapterId(query.getTypeName());
    if (adapterId == null) {
      LOGGER.error("DataTypeAdapter does not exist for type '" + query.getTypeName() + "'");
      return new CloseableIterator.Empty<>();
    }
    if (query.getStatsType() != null) {
      if ((query.getExtendedId() != null) && (query.getExtendedId().length() > 0)) {

        it =
            (CloseableIterator) statisticsStore.getDataStatistics(
                adapterId,
                query.getExtendedId(),
                query.getStatsType(),
                query.getAuthorizations());
      } else {
        it =
            (CloseableIterator) statisticsStore.getDataStatistics(
                adapterId,
                query.getStatsType(),
                query.getAuthorizations());
      }
    } else {
      it =
          (CloseableIterator) statisticsStore.getDataStatistics(
              adapterId,
              query.getAuthorizations());
      if (query.getExtendedId() != null) {
        it =
            new CloseableIteratorWrapper<>(
                it,
                Iterators.filter(it, s -> s.getExtendedId().startsWith(query.getExtendedId())));
      }
    }
  } else {
    if (query.getStatsType() != null) {
      if (query.getExtendedId() != null) {
        it =
            (CloseableIterator) statisticsStore.getDataStatistics(
                query.getExtendedId(),
                query.getStatsType(),
                query.getAuthorizations());
      } else {
        it =
            (CloseableIterator) statisticsStore.getDataStatistics(
                query.getStatsType(),
                query.getAuthorizations());
      }
    } else {
      it = (CloseableIterator) statisticsStore.getAllDataStatistics(query.getAuthorizations());
    }
  }
  return it;
}
 
Example 14
Source File: ParentQueryLogic.java    From datawave with Apache License 2.0 4 votes vote down vote up
@Override
public Iterator<Entry<Key,Value>> iterator() {
    return Iterators.filter(super.iterator(), new DedupeColumnFamilies());
}
 
Example 15
Source File: FilteringIteratorTest.java    From xtext-core with Eclipse Public License 2.0 4 votes vote down vote up
@Test public void testEmptyList() {
	Iterator<String> iter = Iterators.filter(list.iterator(), this);
	assertFalse(iter.hasNext());
}
 
Example 16
Source File: SqlUtil.java    From calcite with Apache License 2.0 4 votes vote down vote up
private static Iterator<SqlOperator> filterOperatorRoutinesByKind(
    Iterator<SqlOperator> routines, final SqlKind sqlKind) {
  return Iterators.filter(routines,
      operator -> Objects.requireNonNull(operator).getKind() == sqlKind);
}
 
Example 17
Source File: FileBasedWorkspace.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public Iterator<? extends FileURI> getFolderIterator(FileURI folderLocation) {
	return Iterators.filter(folderLocation.getAllChildren(), loc -> !loc.isDirectory());
}
 
Example 18
Source File: DataStoreJerseyTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetSplitWithMostContentDeleted() {
    List<Map<String, Object>> content = ImmutableList.<Map<String, Object>>of(
            ImmutableMap.of(Intrinsic.ID, "key1", Intrinsic.DELETED, false, "count", 1),
            ImmutableMap.of(Intrinsic.ID, "key2", Intrinsic.DELETED, true, "count", 2),
            ImmutableMap.of(Intrinsic.ID, "key3", Intrinsic.DELETED, true, "count", 3),
            ImmutableMap.of(Intrinsic.ID, "key4", Intrinsic.DELETED, true, "count", 4),
            ImmutableMap.of(Intrinsic.ID, "key5", Intrinsic.DELETED, false, "count", 5),
            ImmutableMap.of(Intrinsic.ID, "key6", Intrinsic.DELETED, false, "count", 6));

    // Create an iterator which delays 100ms before each deleted value
    Iterator<Map<String, Object>> slowIterator = Iterators.filter(content.iterator(), t -> {
        if (Intrinsic.isDeleted(t)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw Throwables.propagate(e);
            }
        }
        return true; });

    when(_server.getSplit("table-name", "split-name", null, Long.MAX_VALUE, true, ReadConsistency.STRONG)).thenReturn(slowIterator);

    // We need to examine the actual JSON response, so call the API directly
    String response = _resourceTestRule.client().resource("/sor/1/_split/table-name/split-name")
            .queryParam("limit", "2")
            .queryParam("includeDeletes", "false")
            .queryParam("consistency", ReadConsistency.STRONG.toString())
            .header(ApiKeyRequest.AUTHENTICATION_HEADER, APIKEY_TABLE)
            .get(String.class);

    List<Map<String, Object>> actual = JsonHelper.fromJson(response, new TypeReference<List<Map<String, Object>>>() {});

    assertEquals(actual, ImmutableList.of(content.get(0), content.get(4)));
    verify(_server).getSplit("table-name", "split-name", null, Long.MAX_VALUE, true, ReadConsistency.STRONG);
    verifyNoMoreInteractions(_server);

    // Because there was at least 200ms delay between deleted keys 2-4 there should be at least 2 whitespaces between
    // the results which would otherwise not be present.
    int endOfFirstEntry = response.indexOf('}') + 1;
    int commaBeforeSecondEntry = response.indexOf(',', endOfFirstEntry);
    assertTrue(commaBeforeSecondEntry - endOfFirstEntry >= 2);
    assertEquals(Strings.repeat(" ", commaBeforeSecondEntry - endOfFirstEntry), response.substring(endOfFirstEntry, commaBeforeSecondEntry));
}
 
Example 19
Source File: IteratorExtensions.java    From xtext-lib with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Returns the elements of {@code unfiltered} that do not satisfy a predicate. The resulting iterator does not
 * support {@code remove()}. The returned iterator is a view on the original elements. Changes in the unfiltered
 * original are reflected in the view.
 *
 * @param unfiltered
 *            the unfiltered iterator. May not be <code>null</code>.
 * @param predicate
 *            the predicate. May not be <code>null</code>.
 * @return an iterator that contains only the elements that do not fulfill the predicate. Never <code>null</code>.
 */
@Pure
public static <T> Iterator<T> reject(Iterator<T> unfiltered, Function1<? super T, Boolean> predicate) {
	return Iterators.filter(unfiltered, Predicates.not(new BooleanFunctionDelegate<T>(predicate)));
}
 
Example 20
Source File: Entity.java    From stendhal with GNU General Public License v2.0 2 votes vote down vote up
/**
 * an iterator over slots
 *
 * @param slotTypes slot types to include in the iteration
 * @return Iterator
 */
public Iterator<RPSlot> slotIterator(Slots slotTypes) {
	Predicate<RPSlot> p = new SlotNameInList(slotTypes.getNames());
	return Iterators.filter(slotsIterator(), p);
}