com.google.common.collect.Iterators#filter ( )源码实例Demo

下面列出了com.google.common.collect.Iterators#filter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: codebuff   文件: DirectedNodeAdjacencies.java
@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);
    }
  };
}
 
源代码2 项目: geowave   文件: StatisticsRowIterator.java
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)));
  }
}
 
源代码3 项目: xtext-core   文件: ParseResult.java
@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;
		}
	};
}
 
源代码4 项目: ReactionDecoder   文件: Mappings.java
/**
 * 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());
        }
    });
}
 
源代码5 项目: n4js   文件: BlockImpl.java
/**
 * <!-- 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);
}
 
源代码6 项目: xtext-core   文件: AbstractScope.java
@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;
}
 
源代码7 项目: codebuff   文件: DirectedNodeAdjacencies.java
@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);
    }
  };
}
 
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));
        }
    });
}
 
源代码9 项目: phoenix   文件: IndexMaintainer.java
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);
        }
    });
}
 
源代码10 项目: stratio-cassandra   文件: ColumnCondition.java
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);
        }
    });
}
 
源代码11 项目: xtext-core   文件: AbstractNode.java
@Override
public Iterable<ILeafNode> getLeafNodes() {
	return new Iterable<ILeafNode>() {
		@Override
		public Iterator<ILeafNode> iterator() {
			return Iterators.filter(basicIterator(), ILeafNode.class);
		}
	};
}
 
源代码12 项目: aion-germany   文件: MySQL5PlayerEffectsDAO.java
@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);
	}
}
 
源代码13 项目: geowave   文件: BaseDataStore.java
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;
}
 
源代码14 项目: emodb   文件: DataStoreJerseyTest.java
@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));
}
 
源代码15 项目: n4js   文件: FileBasedWorkspace.java
@Override
public Iterator<? extends FileURI> getFolderIterator(FileURI folderLocation) {
	return Iterators.filter(folderLocation.getAllChildren(), loc -> !loc.isDirectory());
}
 
源代码16 项目: calcite   文件: SqlUtil.java
private static Iterator<SqlOperator> filterOperatorRoutinesByKind(
    Iterator<SqlOperator> routines, final SqlKind sqlKind) {
  return Iterators.filter(routines,
      operator -> Objects.requireNonNull(operator).getKind() == sqlKind);
}
 
源代码17 项目: xtext-core   文件: FilteringIteratorTest.java
@Test public void testEmptyList() {
	Iterator<String> iter = Iterators.filter(list.iterator(), this);
	assertFalse(iter.hasNext());
}
 
源代码18 项目: datawave   文件: ParentQueryLogic.java
@Override
public Iterator<Entry<Key,Value>> iterator() {
    return Iterators.filter(super.iterator(), new DedupeColumnFamilies());
}
 
源代码19 项目: xtext-lib   文件: IteratorExtensions.java
/**
 * 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)));
}
 
源代码20 项目: stendhal   文件: Entity.java
/**
 * 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);
}