Java Code Examples for java.util.stream.Stream#filter()

The following examples show how to use java.util.stream.Stream#filter() . These examples are extracted from open source projects. 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
/**
 * Returns ordered list of upgrades that should be applied to the current installation.
 * 
 * @param modelVersions The models and versions currently installed
 * @param localOnly Whether only local upgrades should be selected
 * @return ordered list of upgrades that should be applied
 */
public List<Upgrade> selectUpgrades(final Map<String, String> modelVersions, final boolean localOnly) {

  List<Upgrade> upgrades = upgradeIndex.entrySet().stream()
      .filter(e -> applies(modelVersions, e.getKey()))
      .map(e -> e.getValue())
      .collect(toList());

  List<String> problems = new ArrayList<>();
  upgrades.forEach(u -> checkUpgrade(u, problems));
  if (!problems.isEmpty()) {
    String message = String.format("Found %d problem(s) with upgrades:%n%s",
        problems.size(), problems.stream().collect(joining(lineSeparator())));
    throw new IllegalStateException(message);
  }

  Stream<UpgradeStep> upgradeSteps = order(modelVersions, upgrades);
  if (localOnly) {
    upgradeSteps = upgradeSteps.filter(step -> localModels.contains(step.getModel()));
  }

  return upgradeSteps
      .map(UpgradeStep::getUpgrade)
      .collect(toList());
}
 
Example 2
Source Project: buck   File: BuckConfig.java    License: Apache License 2.0 6 votes vote down vote up
public Optional<ImmutableList<Path>> getOptionalPathList(
    String section, String field, boolean resolve) {
  Optional<ImmutableList<String>> rawPaths =
      config.getOptionalListWithoutComments(section, field);

  if (!rawPaths.isPresent()) {
    return Optional.empty();
  }

  Stream<Path> paths = rawPaths.get().stream().map(this::getPathFromVfs);
  if (resolve) {
    paths = paths.map(projectFilesystem::getPathForRelativePath);
  }
  paths = paths.filter(projectFilesystem::exists);

  return Optional.of(paths.collect(ImmutableList.toImmutableList()));
}
 
Example 3
@Override
public Stream<User> getMembers(DateTime when) {
    Stream<Student> students = Bennu.getInstance().getStudentsSet().stream();

    if (registered == null) {
        students = students.filter(student -> student.getAlumni() != null || hasConcludedRegistration(student) || isAlumni(student));
    }
    else if (registered) {
        students = students.filter(student -> student.getAlumni() != null && isAlumni(student));
    }
    else {
        students = students.filter(student -> student.getAlumni() == null && hasConcludedRegistration(student) && !isAlumni(student));
    }

    // If degree is set, filter out the alumni that didn't conclude the specified degree
    if (degree != null) {
        students = students.filter(this::isDegreeConcluded);
    }

    // Join students in a collection of users
    return students.map(student -> student.getPerson().getUser());
}
 
Example 4
Source Project: extract   File: MetadataTransformer.java    License: MIT License 6 votes vote down vote up
private void transform(final String normalisedName, String[] values, final ValueArrayConsumer consumer) throws
		IOException {
	Stream<String> stream = Arrays.stream(values);

	// Remove empty values.
	stream = stream.filter(value -> null != value && !value.isEmpty());

	// Remove duplicates.
	// Normalised to lowercase so that "GENERATOR" matches "Generator" (these inconsistent names can come from
	// HTML documents).
	if (values.length > 1 && deduplicateProperties.contains(fieldMap.get(normalisedName)
			.toLowerCase(Locale.ENGLISH))) {
		stream = stream.distinct();
	}

	values = stream.toArray(String[]::new);
	if (values.length > 0) {
		consumer.accept(normalisedName, values);
	}
}
 
Example 5
Source Project: vertexium   File: RangeFunction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ExecutionStepWithResultName create(String resultName, boolean distinct, ExecutionStepWithResultName[] argumentsExecutionStep) {
    if (distinct) {
        throw new VertexiumCypherNotImplemented("distinct");
    }
    return new FunctionInvocationExecutionStep(getClass().getSimpleName(), resultName, argumentsExecutionStep) {
        @Override
        protected Object executeFunction(VertexiumCypherQueryContext ctx, Object[] arguments) {
            if (arguments.length > 3) {
                throw new VertexiumException("range function takes 2 or 3 arguments");
            }
            int arg0 = argumentToInt(arguments[0]);
            int arg1 = argumentToInt(arguments[1]);
            Stream<Integer> result = IntStream.rangeClosed(arg0, arg1).boxed();
            if (arguments.length == 3) {
                int step = argumentToInt(arguments[2]);
                if (step == 0) {
                    throw new VertexiumCypherArgumentErrorException("NumberOutOfRange: step must be greater than 0");
                }
                result = result.filter(i -> i % step == 0);
            }
            return result;
        }
    };
}
 
Example 6
@VisibleForTesting
String[] getSearchableIndexes(final RepositoryQueryBuilder repoQuery) {
  Stream<Repository> repositories = StreamSupport
      .stream(repositoryManager.browse().spliterator(), false)
      .filter(SearchQueryServiceImpl::repoOnlineAndHasSearchIndexFacet);

  if (repoQuery.repositoryNames != null) {
    repositories = repositories
        .filter(r -> repoQuery.repositoryNames.contains(r.getName()));
  }

  if (repoQuery.skipContentSelectors) {
    // not post-filtering by content selector, so we must pre-filter repositories we can access
    repositories = repositories
        .filter(r -> securityHelper.allPermitted(new RepositoryViewPermission(r, BROWSE)));
  }

  return repositories
      .map(indexNamingPolicy::indexName)
      .toArray(String[]::new);
}
 
Example 7
public Stream<AddressEntry> getAddressEntriesForAvailableBalanceStream() {
    Stream<AddressEntry> availableOrPayout = Stream.concat(btcWalletService.getAddressEntries(AddressEntry.Context.TRADE_PAYOUT)
            .stream(), btcWalletService.getFundedAvailableAddressEntries().stream());
    Stream<AddressEntry> available = Stream.concat(availableOrPayout,
            btcWalletService.getAddressEntries(AddressEntry.Context.ARBITRATOR).stream());
    available = Stream.concat(available, btcWalletService.getAddressEntries(AddressEntry.Context.OFFER_FUNDING).stream());
    return available.filter(addressEntry -> btcWalletService.getBalanceForAddress(addressEntry.getAddress()).isPositive());
}
 
Example 8
Source Project: geowave   File: RocksDBReader.java    License: Apache License 2.0 5 votes vote down vote up
private Iterator<GeoWaveRow> createIteratorForDataIndexReader(
    final RocksDBClient client,
    final DataIndexReaderParams dataIndexReaderParams) {
  final RocksDBDataIndexTable dataIndexTable =
      RocksDBUtils.getDataIndexTable(
          client,
          dataIndexReaderParams.getInternalAdapterStore().getTypeName(
              dataIndexReaderParams.getAdapterId()),
          dataIndexReaderParams.getAdapterId());
  Iterator<GeoWaveRow> iterator;
  if (dataIndexReaderParams.getDataIds() != null) {
    iterator = dataIndexTable.dataIndexIterator(dataIndexReaderParams.getDataIds());
  } else {
    iterator =
        dataIndexTable.dataIndexIterator(
            dataIndexReaderParams.getStartInclusiveDataId(),
            dataIndexReaderParams.getEndInclusiveDataId());
  }
  if (client.isVisibilityEnabled()) {
    Stream<GeoWaveRow> stream = Streams.stream(iterator);
    final Set<String> authorizations =
        Sets.newHashSet(dataIndexReaderParams.getAdditionalAuthorizations());
    stream = stream.filter(new ClientVisibilityFilter(authorizations));
    iterator = stream.iterator();
  }
  return iterator;
}
 
Example 9
@Override
public void delete(Stream<FileMeta> fileMetaStream) {
  super.delete(
      fileMetaStream.filter(
          fileMeta -> {
            this.deleteFile(fileMeta);
            return true;
          }));
}
 
Example 10
Source Project: arcusplatform   File: FilteredViewModel.java    License: Apache License 2.0 5 votes vote down vote up
protected void rebuildView() {
   Stream<M> stream = StreamSupport.stream(delegate.spliterator(), false);
   if(filter != null) {
      stream = stream.filter(filter);
   }
   if(comparator != null) {
      stream = stream.sorted(comparator);
   }
   this.view = stream.collect(Collectors.toList());
   this.listeners.fireEvent(ViewModelEvent.changed());
}
 
Example 11
@Override
public List<Map> get(DataFetchingEnvironment env) {
  if (env.getSource() instanceof SubjectReference) {
    final Set<String> dataSetIds = new HashSet<>();
    SubjectReference source = env.getSource();
    ContextData contextData = env.getContext();
    Stream<DataSet> dataSets = contextData.getUser()
      .map(user -> repo.getDataSetsWithReadAccess(user).stream())
      .orElseGet(() -> repo.getDataSets().stream().filter(d -> d.getMetadata().isPublished()));

    if (env.containsArgument("dataSetIds")) {
      dataSetIds.addAll(env.getArgument("dataSetIds"));
      dataSets = dataSets.filter(d -> dataSetIds.contains(d.getMetadata().getCombinedId()));
    }
    final String ownId = source.getDataSet().getMetadata().getCombinedId();
    return dataSets
      .filter(d -> !ownId.equals(d.getMetadata().getCombinedId()))
      .map(d -> {
        try (Stream<CursorQuad> quads = d.getQuadStore().getQuads(source.getSubjectUri())) {
          return tuple(d, quads.findAny());
        }
      })
      .filter(i -> i.getRight().isPresent())
      .map(i -> ImmutableMap.of(
        "metadata", new DataSetWithDatabase(i.getLeft(), env.<ContextData>getContext().getUserPermissionCheck()),
        "entity", new LazyTypeSubjectReference(i.getRight().get().getSubject(), i.getLeft())
      ))
      .collect(toList());

  }
  return Lists.newArrayList();
}
 
Example 12
@Override
public Collection<SubscriptionEntity> search(SubscriptionQuery query) {
    try {
        logger.debug("Search subscriptions {}", query);

        SubscriptionCriteria.Builder builder = new SubscriptionCriteria.Builder()
                .apis(query.getApis())
                .applications(query.getApplications())
                .plans(query.getPlans())
                .from(query.getFrom())
                .to(query.getTo());

        if (query.getStatuses() != null) {
            builder.statuses(
            query.getStatuses().stream()
                    .map(subscriptionStatus -> Subscription.Status.valueOf(subscriptionStatus.name()))
                    .collect(Collectors.toSet()));
        }

        Stream<SubscriptionEntity> subscriptionsStream =
                subscriptionRepository.search(builder.build()).stream().map(this::convert);
        if (query.getApiKey() != null && !query.getApiKey().isEmpty()) {
            subscriptionsStream = subscriptionsStream.filter(subscriptionEntity -> {
                final Set<ApiKeyEntity> apiKeys = apiKeyService.findBySubscription(subscriptionEntity.getId());
                return apiKeys.stream().anyMatch(apiKeyEntity -> apiKeyEntity.getKey().equals(query.getApiKey()));
            });
        }
        return subscriptionsStream.collect(toList());
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to search for subscriptions: {}", query, ex);
        throw new TechnicalManagementException(
                String.format("An error occurs while trying to search for subscriptions: %s", query), ex);
    }
}
 
Example 13
private Stream<Attribute> filterPermission(
    Stream<Attribute> attrs, EntityTypePermission permission) {
  return attrs.filter(
      attr ->
          permissionService.hasPermission(
              new EntityTypeIdentity(attr.getEntity().getId()), permission));
}
 
Example 14
private Stream<Person> filterEmail(Stream<Person> matches) {
    if (!Strings.isNullOrEmpty(email)) {
        if (matches == null) {
            return EmailAddress.findAllActiveAndValid(email).filter(Objects::nonNull).map(EmailAddress::getParty)
                    .filter(Objects::nonNull).filter(party -> party.isPerson()).map(Person.class::cast)
                    .filter(Objects::nonNull).filter(Objects::nonNull);
        } else {
            return matches.filter(p -> p.getEmailAddressStream()
                    .filter(emailAddress -> emailAddress.getValue().equals(email))
                    .filter(emailAddress -> emailAddress.isActiveAndValid()).findAny().isPresent());
        }
    }
    return matches;
}
 
Example 15
Source Project: tutorials   File: OptionalToStreamUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testOptionalToStream() {
    Optional<String> op = Optional.ofNullable("String value");
    Stream<String> strOptionalStream = op.stream();
    Stream<String> filteredStream = strOptionalStream.filter((str) -> {
        return str != null && str.startsWith("String");
    });
    assertEquals(1, filteredStream.count());

}
 
Example 16
private List<ICartHopperBehaviour<?>> getApplicableHopperBehaviours(EntityMinecart cart){
    Stream<ICartHopperBehaviour<?>> behaviours = RailManager.getInstance().getHopperBehaviours().stream();
    behaviours = behaviours.filter(hopperBehaviour -> interactEngine && hopperBehaviour instanceof CartHopperBehaviourItems || managingCart.hasCapability(hopperBehaviour.getCapability(), null));
    return behaviours.collect(Collectors.toList());
}
 
Example 17
protected Accessor findAccessor(Class<?> targetClass, Cache<Class<?>, Accessor> cache, Kind kind, Set<Class<?>> visitedInterfaces) {
    Accessor accessor = findDeclaredAccessor(targetClass, kind);
    if (null != accessor) {
        return accessor;
    }

    if (inspectSuperclasses) {
        Class<?> superClass = targetClass.getSuperclass();
        if (null != superClass && Object.class != superClass) {
            accessor = getAccessor(superClass, cache, kind, visitedInterfaces);
            if (null != accessor && checkVisibility && !accessor.isVisibleTo(targetClass)) {
                accessor = null;
            }
        }
    }

    List<Accessor> superAccessors = new ArrayList<>();
    if (accessor != null) {
        if (superClassPriority) {
            return accessor;
        } else {
            superAccessors.add(accessor);
        }
    } 
    
    if (inspectInterfaces) {
        Stream<Accessor> accessorsByInterfaces = Stream.of(targetClass.getInterfaces())
            .filter(i -> !visitedInterfaces.contains(i))
            .peek(i -> visitedInterfaces.add(i))
            .map(i -> getAccessor(i, cache, kind, visitedInterfaces))
            .filter(Objects::nonNull);
        
        if (checkVisibility) {
            accessorsByInterfaces = accessorsByInterfaces.filter(a -> a.isVisibleTo(targetClass));
        }
        
        List<Accessor> accessors = accessorsByInterfaces
            //.limit(2)
            .collect(Collectors.toList());
        superAccessors.addAll(accessors);
    }
    
    
    switch (superAccessors.size()) {
        case 0: return null;
        case 1: return superAccessors.get(0);
        default:
            throw new IllegalStateException(
                "Ambiguity: class " + targetClass.getName() + " has more than one " +
                SchedulerProvider.class.getSimpleName() + " defined by inherited accessors:\n" +
                superAccessors.toString()
            );                    
    }
}
 
Example 18
private void attack()
{
	// set entity
	ClientPlayerEntity player = MC.player;
	ClientWorld world = MC.world;
	
	if(player.getAttackCooldownProgress(0) < 1)
		return;
	
	double rangeSq = Math.pow(range.getValue(), 2);
	Stream<LivingEntity> stream = StreamSupport
		.stream(MC.world.getEntities().spliterator(), true)
		.filter(e -> e instanceof LivingEntity).map(e -> (LivingEntity)e)
		.filter(e -> !e.removed && e.getHealth() > 0)
		.filter(e -> player.squaredDistanceTo(e) <= rangeSq)
		.filter(e -> e != player)
		.filter(e -> !(e instanceof FakePlayerEntity))
		.filter(e -> !WURST.getFriends().contains(e.getEntityName()));
	
	if(filterPlayers.isChecked())
		stream = stream.filter(e -> !(e instanceof PlayerEntity));
	
	if(filterSleeping.isChecked())
		stream = stream.filter(e -> !(e instanceof PlayerEntity
			&& ((PlayerEntity)e).isSleeping()));
	
	if(filterFlying.getValue() > 0)
		stream = stream.filter(e -> {
			
			if(!(e instanceof PlayerEntity))
				return true;
			
			Box box = e.getBoundingBox();
			box = box.union(box.offset(0, -filterFlying.getValue(), 0));
			return world.doesNotCollide(box);
		});
	
	if(filterMonsters.isChecked())
		stream = stream.filter(e -> !(e instanceof Monster));
	
	if(filterPigmen.isChecked())
		stream = stream.filter(e -> !(e instanceof ZombifiedPiglinEntity));
	
	if(filterEndermen.isChecked())
		stream = stream.filter(e -> !(e instanceof EndermanEntity));
	
	if(filterAnimals.isChecked())
		stream = stream.filter(
			e -> !(e instanceof AnimalEntity || e instanceof AmbientEntity
				|| e instanceof WaterCreatureEntity));
	
	if(filterBabies.isChecked())
		stream = stream.filter(e -> !(e instanceof PassiveEntity
			&& ((PassiveEntity)e).isBaby()));
	
	if(filterPets.isChecked())
		stream = stream
			.filter(e -> !(e instanceof TameableEntity
				&& ((TameableEntity)e).isTamed()))
			.filter(e -> !(e instanceof HorseBaseEntity
				&& ((HorseBaseEntity)e).isTame()));
	
	if(filterVillagers.isChecked())
		stream = stream.filter(e -> !(e instanceof VillagerEntity));
	
	if(filterGolems.isChecked())
		stream = stream.filter(e -> !(e instanceof GolemEntity));
	
	if(filterInvisible.isChecked())
		stream = stream.filter(e -> !e.isInvisible());
	
	LivingEntity target =
		stream.min(priority.getSelected().comparator).orElse(null);
	if(target == null)
		return;
	
	WURST.getHax().autoSwordHack.setSlot();
	
	// face entity
	Rotation rotation = RotationUtils
		.getNeededRotations(target.getBoundingBox().getCenter());
	PlayerMoveC2SPacket.LookOnly packet = new PlayerMoveC2SPacket.LookOnly(
		rotation.getYaw(), rotation.getPitch(), MC.player.isOnGround());
	MC.player.networkHandler.sendPacket(packet);
	
	// attack entity
	MC.interactionManager.attackEntity(player, target);
	player.swingHand(Hand.MAIN_HAND);
}
 
Example 19
@Override
public void update(Stream<RoleMembership> roleMembershipStream) {
  super.update(roleMembershipStream.filter(this::preUpdate));
}
 
Example 20
public static <T> Stream<T> instancesOf(Stream<?> stream, Class<T> type) {
    return (Stream<T>) stream.filter(type::isInstance);
}