Java Code Examples for java.util.function.Predicate#negate()

The following examples show how to use java.util.function.Predicate#negate() . 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: AppQuestCondition.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * 条件(論理演算)
 *
 * @param ships 艦隊
 * @return 条件に一致する場合true
 */
private boolean testOperator(List<ShipMst> ships) {
    Predicate<List<ShipMst>> predicate = null;
    for (FleetCondition condition : this.conditions) {
        if (predicate == null) {
            predicate = condition;
        } else {
            predicate = this.operator.endsWith("AND")
                    ? predicate.and(condition)
                    : predicate.or(condition);
        }
    }
    if ("NAND".equals(this.operator) || "NOR".equals(this.operator)) {
        predicate = predicate.negate();
    }
    return predicate.test(new ArrayList<>(ships));
}
 
Example 2
Source File: Test38.java    From blog with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args) {
	List<Apple> inventory = Arrays.asList(new Apple("green", 200), new Apple("red", 100), new Apple("black", 110),
			new Apple("blue", 300));

	// 1.比较器复合
	// 逆序
	inventory.sort(comparing(Apple::getWeight).reversed());

	// 比较器链
	inventory.sort(comparing(Apple::getWeight).reversed().thenComparing(Apple::getColor));

	// 2.谓词复合
	Predicate<Apple> redApple = (Apple a) -> "red".equals(a.getColor());
	Predicate<Apple> notRedApple = redApple.negate();
	Predicate<Apple> redAndHeavyAppleOrGreen = redApple.and(a -> a.getWeight() > 150)
			.or(a -> "green".equals(a.getColor()));

	// 3.函数复合
	Function<Integer, Integer> f = x -> x + 1;
	Function<Integer, Integer> g = x -> x * 2;
	Function<Integer, Integer> h = f.andThen(g);
	int result = h.apply(1);
	System.out.println(result);
}
 
Example 3
Source File: MissionCondition.java    From logbook-kai with MIT License 6 votes vote down vote up
/**
 * 条件(論理演算)
 *
 * @param ships 艦隊
 * @return 条件に一致する場合true
 */
private boolean testOperator(List<Ship> ships) {
    Predicate<List<Ship>> predicate = null;
    for (MissionCondition condition : this.conditions) {
        if (predicate == null) {
            predicate = condition;
        } else {
            predicate = this.operator.endsWith("AND")
                    ? predicate.and(condition)
                    : predicate.or(condition);
        }
    }
    if ("NAND".equals(this.operator) || "NOR".equals(this.operator)) {
        predicate = predicate.negate();
    }
    return predicate.test(new ArrayList<>(ships));
}
 
Example 4
Source File: ConfigurableClassLoaderTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void jvmOnlyInParentSpi() throws IOException {
    final Predicate<String> parentClasses = name -> true;
    try (final URLClassLoader parent =
            new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader());
            final ConfigurableClassLoader loader = new ConfigurableClassLoader("test", new URL[0], parent,
                    parentClasses, parentClasses.negate(), new String[0], new String[] {
                            new File(System.getProperty("java.home")).toPath().toAbsolutePath().toString() })) {

        // can be loaded cause in the JVM
        assertTrue(ServiceLoader.load(FileSystemProvider.class, loader).iterator().hasNext());

        // this is in the (test) classloader but not available to the classloader
        final List<TestEngine> junitEngines = StreamSupport
                .stream(ServiceLoader.load(TestEngine.class, loader).spliterator(), false)
                .collect(toList());
        assertTrue(junitEngines.isEmpty());
    }
}
 
Example 5
Source File: ConfigurableClassLoaderTest.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Test
void excludedSpiResources() throws Exception {
    final Predicate<String> parentClasses = name -> true;
    final File xerces = new File(Constants.DEPENDENCIES_LOCATION, "xerces/xercesImpl/2.12.0/xercesImpl-2.12.0.jar");
    assertTrue(xerces.exists());
    try (final URLClassLoader parent =
            new URLClassLoader(new URL[0], Thread.currentThread().getContextClassLoader());
            final ConfigurableClassLoader loader = new ConfigurableClassLoader("test",
                    new URL[] { xerces.toURI().toURL() }, parent, parentClasses, parentClasses.negate(),
                    new String[0], new String[] {
                            new File(System.getProperty("java.home")).toPath().toAbsolutePath().toString() })) {

        final Thread thread = Thread.currentThread();
        final ClassLoader old = thread.getContextClassLoader();
        thread.setContextClassLoader(loader);
        try {
            assertXmlReader();
        } finally {
            thread.setContextClassLoader(old);
        }
        assertXmlReader();
    }
}
 
Example 6
Source File: MessagesService.java    From BungeeChat2 with GNU General Public License v3.0 6 votes vote down vote up
public static void sendLocalMessage(BungeeChatContext context) throws InvalidContextError {
  context.require(BungeeChatContext.HAS_SENDER, BungeeChatContext.HAS_MESSAGE);

  Optional<BungeeChatAccount> account = context.getSender();
  Optional<String> finalMessage = preProcessMessage(context, Format.LOCAL_CHAT);
  String localServerName =
      context.hasServer() ? context.getServer().get() : context.getSender().get().getServerName();
  Predicate<BungeeChatAccount> isLocal = getLocalPredicate(localServerName);
  Predicate<BungeeChatAccount> notIgnored = getNotIgnoredPredicate(account);

  sendToMatchingPlayers(finalMessage, isLocal, notIgnored);

  ChatLoggingManager.logMessage(ChannelType.LOCAL, context);

  if (ModuleManager.isModuleActive(BungeecordModuleManager.SPY_MODULE)) {
    String localSpyMessage = preProcessMessage(context, account, Format.LOCAL_SPY, false).get();
    Predicate<BungeeChatAccount> isNotLocal = isLocal.negate();

    sendToMatchingPlayers(
        localSpyMessage, BungeeChatAccount::hasLocalSpyEnabled, isNotLocal, notIgnored);
  }
}
 
Example 7
Source File: BankAccount_attachPdfAsIbanProof.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Action(
        semantics = SemanticsOf.IDEMPOTENT,
        commandDtoProcessor = DeriveBlobFromDummyPdfArg0.class
)
public BankAccount act(
        @Parameter(fileAccept = MimeTypeData.Str.APPLICATION_PDF)
        final Blob document) {

    final DocumentType ibanProofDocType = DocumentTypeData.IBAN_PROOF.findUsing(documentTypeRepository);

    final List<Paperclip> ibanProofPaperclips =
            paperclipRepository.findByAttachedToAndRoleName(bankAccount, ROLE_NAME_FOR_IBAN_PROOF);

    // delete all existing paperclips for this role whose type is also not IBAN_PROOF
    // (ie any incoming invoices that were automatically attached as candidate iban proofs)
    final Predicate<Paperclip> hasIbanProofDocType =
            paperclip -> Objects.equals(ibanProofDocType, paperclip.getDocument().getType());
    final Predicate<Paperclip> doesNotHaveIbanProofDocType = hasIbanProofDocType.negate();

    ibanProofPaperclips.stream()
            .filter(doesNotHaveIbanProofDocType).forEach(
                paperclip -> paperclipRepository.delete(paperclip)
            );

    final String name = document.getName();
    documentService.createAndAttachDocumentForBlob(
            ibanProofDocType, bankAccount.getAtPath(), name, document, ROLE_NAME_FOR_IBAN_PROOF, bankAccount);
    return bankAccount;
}
 
Example 8
Source File: PrintablePredicateTest.java    From objectlabkit with Apache License 2.0 5 votes vote down vote up
@Test
public void testAnd() {
    // now Combine them:
    final Predicate<Asset> activeBondOrEquity = hasAssetClass("Equity", "Bond").and(hasState("Active"));
    assertThat(activeBondOrEquity.toString()).isEqualToIgnoringCase("AssetClass in (Equity, Bond) AND State=Active");
    // does it work?
    assertThat(activeBondOrEquity.test(new Asset("Equity", "Stock", "Active"))).isTrue();
    assertThat(activeBondOrEquity.test(new Asset("Bond", "Corporate Bond", "Active"))).isTrue();
    assertThat(activeBondOrEquity.test(new Asset("Bond", "Government Bond", "Matured"))).isFalse();

    // let's try negate
    final Predicate<Asset> notActiveBondOrEquity = activeBondOrEquity.negate();
    assertThat(notActiveBondOrEquity.toString()).isEqualToIgnoringCase("NOT (AssetClass in (Equity, Bond) AND State=Active)");
}
 
Example 9
Source File: Prelude.java    From pitest with Apache License 2.0 4 votes vote down vote up
public static final <A> Predicate<A> not(final Predicate<A> p) {
  return p.negate();
}
 
Example 10
Source File: Main.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        List<Melon> melons1 = Arrays.asList(new Melon("Gac", 2000),
                new Melon("Horned", 1600), new Melon("Apollo", 3000),
                new Melon("Gac", 3000), new Melon("Hemi", 1600));

        Comparator<Melon> byWeight = Comparator.comparing(Melon::getWeight);
        Comparator<Melon> byType = Comparator.comparing(Melon::getType);

        Comparator<Melon> byWeightAndType = Comparator.comparing(Melon::getWeight)
                .thenComparing(Melon::getType);               

        List<Melon> sortedMelons1 = melons1.stream()
                .sorted(byWeight)               
                .collect(Collectors.toList());

        List<Melon> sortedMelons2 = melons1.stream()
                .sorted(byType)
                .collect(Collectors.toList());

        List<Melon> sortedMelons3 = melons1.stream()
                .sorted(byWeightAndType)
                .collect(Collectors.toList());

        System.out.println("Unsorted melons: " + melons1);
        System.out.println("\nSorted by weight melons: " + sortedMelons1);
        System.out.println("Sorted by type melons: " + sortedMelons2);
        System.out.println("Sorted by weight and type melons: " + sortedMelons3);
        
        List<Melon> melons2 = Arrays.asList(new Melon("Gac", 2000),
                new Melon("Horned", 1600), new Melon("Apollo", 3000),
                new Melon("Gac", 3000), new Melon("hemi", 1600));
        
        Comparator<Melon> byWeightAndType2 = Comparator.comparing(Melon::getWeight)
                .thenComparing(Melon::getType, String.CASE_INSENSITIVE_ORDER);

        List<Melon> sortedMelons4 = melons2.stream()
                .sorted(byWeightAndType2)
                .collect(Collectors.toList());
        
        System.out.println("\nSorted by weight and type (case insensitive) melons: " + sortedMelons4);
        
        Predicate<Melon> p2000 = m -> m.getWeight() > 2000;
        Predicate<Melon> p2000GacApollo = p2000.and(m -> m.getType().equals("Gac"))
                .or(m -> m.getType().equals("Apollo"));
        Predicate<Melon> restOf = p2000GacApollo.negate();
        Predicate<Melon> pNot2000 = Predicate.not(m -> m.getWeight() > 2000);        

        List<Melon> result1 = melons1.stream()
                .filter(p2000GacApollo)
                .collect(Collectors.toList());

        List<Melon> result2 = melons1.stream()
                .filter(restOf)
                .collect(Collectors.toList());
        
        List<Melon> result3 = melons1.stream()
                .filter(pNot2000)
                .collect(Collectors.toList());

        System.out.println("\nAll melons of type Apollo or Gac heavier than 2000 grams:\n" + result1);       
        System.out.println("\nNegation of the above predicate:\n" + result2);
        System.out.println("\nAll melons lighter than (or equal to) 2000 grams:\n" + result3);

        Function<Double, Double> f = x -> x * 2;
        Function<Double, Double> g = x -> Math.pow(x, 2);
        Function<Double, Double> gf = f.andThen(g);
        Function<Double, Double> fg = f.compose(g);
        double resultgf = gf.apply(4d);
        double resultfg = fg.apply(4d);

        System.out.println("\ng(f(x)): " + resultgf);
        System.out.println("f(g(x)): " + resultfg);
                
        Function<String, String> introduction = Editor::addIntroduction;
        Function<String, String> editor = introduction.andThen(Editor::addBody)
                .andThen(Editor::addConclusion);

        String article = editor.apply("\nArticle name\n");

        System.out.println(article);
    }
 
Example 11
Source File: ClassPropertyGenerator.java    From es6draft with MIT License 4 votes vote down vote up
private static <T> Predicate<T> not(Predicate<T> pred) {
    return pred.negate();
}
 
Example 12
Source File: ArtifactsToOwnerLabels.java    From bazel with Apache License 2.0 4 votes vote down vote up
public Builder filterArtifacts(Predicate<Artifact> artifactsToKeep) {
  Predicate<Artifact> artifactsToRemove = artifactsToKeep.negate();
  artifactToMultipleOrDifferentOwnerLabels.keySet().removeIf(artifactsToRemove);
  artifactsOwnedOnlyByTheirLabels.removeIf(artifactsToRemove);
  return this;
}
 
Example 13
Source File: Predicates.java    From cyclops with Apache License 2.0 4 votes vote down vote up
public static <T1> Predicate<T1> not(final Predicate<T1> p) {
    return p.negate();
}
 
Example 14
Source File: LaunchHandler.java    From corrosion with Eclipse Public License 2.0 4 votes vote down vote up
private static <T> Predicate<T> not(Predicate<T> p) {
	return p.negate();
}
 
Example 15
Source File: JavaUtil.java    From jeddict with Apache License 2.0 4 votes vote down vote up
public static <R> Predicate<R> not(Predicate<R> predicate) {
    return predicate.negate();
}
 
Example 16
Source File: MCRStreamUtils.java    From mycore with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Negates a predicate.
 *
 * @see <a href="https://stackoverflow.com/questions/28235764/how-can-i-negate-a-lambda-predicate">stackoverflow</a>
 * @param predicate the predicate to negate
 * @return the negated predicate
 */
public static <T> Predicate<T> not(Predicate<T> predicate) {
    return predicate.negate();
}
 
Example 17
Source File: Guavate.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a predicate that negates the original.
 * <p>
 * The JDK provides {@link Predicate#negate()} however this requires a predicate.
 * Sometimes, it can be useful to have a static method to achieve this.
 * <pre>
 *  stream.filter(not(String::isEmpty))
 * </pre>
 *
 * @param <R>  the type of the object the predicate works on
 * @param predicate  the predicate to negate
 * @return the negated predicate
 */
public static <R> Predicate<R> not(Predicate<R> predicate) {
  return predicate.negate();
}
 
Example 18
Source File: Predicates.java    From arctic-sea with Apache License 2.0 2 votes vote down vote up
/**
 * Negates the predicate.
 *
 * @param <T>       the type of the input to the predicate
 * @param predicate the predicate to negate
 *
 * @return the negated predicate
 */
public static <T> Predicate<T> not(Predicate<T> predicate) {
    return predicate.negate();
}
 
Example 19
Source File: Predicates.java    From unix-stream with MIT License 2 votes vote down vote up
/**
 * Create a new predicate that excludes elements matching the given predicate from a stream.
 * This is the opposite behavior of {@link Stream#filter(java.util.function.Predicate)}.
 *
 * @param predicate the predicate to apply
 * @param <T>       the type of objects the predicate will be applied on
 * @return a new predicate excluding elements matching the given predicate from a stream.
 */
public static <T> Predicate<T> exclude(final Predicate<T> predicate) {
    Objects.requireNonNull(predicate, "The predicate must not be null");
    return predicate.negate();
}
 
Example 20
Source File: Helper.java    From tilesfx with Apache License 2.0 votes vote down vote up
public static final <T> Predicate<T> not(final Predicate<T> PREDICATE) { return PREDICATE.negate(); }