public void testToImmutableSetMultimap() { Collector<Entry<String, Integer>, ?, ImmutableSetMultimap<String, Integer>> collector = ImmutableSetMultimap.toImmutableSetMultimap(Entry::getKey, Entry::getValue); BiPredicate<ImmutableSetMultimap<?, ?>, ImmutableSetMultimap<?, ?>> equivalence = Equivalence.equals() .onResultOf( (ImmutableSetMultimap<?, ?> mm) -> ImmutableListMultimap.copyOf(mm).asMap().entrySet().asList()) .and(Equivalence.equals()); CollectorTester.of(collector, equivalence) .expectCollects(ImmutableSetMultimap.of()) .expectCollects( ImmutableSetMultimap.of("a", 1, "b", 2, "a", 3, "c", 4), mapEntry("a", 1), mapEntry("b", 2), mapEntry("a", 3), mapEntry("c", 4)); }
public void testFlatteningToImmutableListMultimap() { Collector<String, ?, ImmutableListMultimap<Character, Character>> collector = ImmutableListMultimap.flatteningToImmutableListMultimap( str -> str.charAt(0), str -> str.substring(1).chars().mapToObj(c -> (char) c)); BiPredicate<Multimap<?, ?>, Multimap<?, ?>> equivalence = Equivalence.equals() .onResultOf((Multimap<?, ?> mm) -> ImmutableList.copyOf(mm.asMap().entrySet())) .and(Equivalence.equals()); ImmutableListMultimap<Character, Character> empty = ImmutableListMultimap.of(); ImmutableListMultimap<Character, Character> filled = ImmutableListMultimap.<Character, Character>builder() .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')) .putAll('a', Arrays.asList('p', 'p', 'l', 'e')) .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')) .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')) .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')) .build(); CollectorTester.of(collector, equivalence) .expectCollects(empty) .expectCollects(filled, "banana", "apple", "carrot", "asparagus", "cherry"); }
/** * Null-safely convert between two maps by applying a function to each key and value. A predicate is also specified to filter * the results, in case the mapping function were to generate duplicate keys, etc. */ public static <T1, T2, U1, U2> Map<U1, U2> convert(Map<T1, T2> toConvert, Function<? super T1, ? extends U1> keyConverter, Function<? super T2, ? extends U2> valueConverter, BiPredicate<U1, U2> resultFilter) { if (toConvert == null) { return null; } Map<U1, U2> result = toConvert.entrySet().stream() .map(e -> new SimpleImmutableEntry<>(keyConverter.apply(e.getKey()), valueConverter.apply(e.getValue()))) .filter(p -> resultFilter.test(p.getKey(), p.getValue())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); return Collections.unmodifiableMap(result); }
@Nonnull @Override public SingleSubscriptionBuilder<T> expireIf(@Nonnull BiPredicate<SingleSubscription<T>, T> predicate, @Nonnull ExpiryTestStage... testPoints) { Preconditions.checkNotNull(testPoints, "testPoints"); Preconditions.checkNotNull(predicate, "predicate"); for (ExpiryTestStage testPoint : testPoints) { switch (testPoint) { case PRE: preExpiryTests.add(predicate); break; case POST_FILTER: midExpiryTests.add(predicate); break; case POST_HANDLE: postExpiryTests.add(predicate); break; default: throw new IllegalArgumentException("Unknown ExpiryTestPoint: " + testPoint); } } return this; }
@Nonnull @Override public MergedSubscriptionBuilder<T> expireIf(@Nonnull BiPredicate<MergedSubscription<T>, T> predicate, @Nonnull ExpiryTestStage... testPoints) { Preconditions.checkNotNull(testPoints, "testPoints"); Preconditions.checkNotNull(predicate, "predicate"); for (ExpiryTestStage testPoint : testPoints) { switch (testPoint) { case PRE: preExpiryTests.add(predicate); break; case POST_FILTER: midExpiryTests.add(predicate); break; case POST_HANDLE: postExpiryTests.add(predicate); break; default: throw new IllegalArgumentException("Unknown ExpiryTestPoint: " + testPoint); } } return this; }
/** * Finds all values matching the predicate, returns as a map. */ public static <K,V> Map<K,V> findAll(Map<K,V> receiver, BiPredicate<K,V> predicate) { // try to preserve some properties of the receiver (see the groovy javadocs) final Map<K,V> map; if (receiver instanceof TreeMap) { map = new TreeMap<>(); } else { map = new LinkedHashMap<>(); } for (Map.Entry<K,V> kvPair : receiver.entrySet()) { if (predicate.test(kvPair.getKey(), kvPair.getValue())) { map.put(kvPair.getKey(), kvPair.getValue()); } } return map; }
private int _search(final List<K> list, final int start, final int end, final BiPredicate<K,K> isGreater, final K searchable) { final int mid = (start + end) / 2; if(list.get(mid) == searchable) return mid; if(start == end) { if (isGreater.test(list.get(mid), searchable)) { return mid; } else { return mid + 1; } } if(isGreater.test(list.get(mid), searchable)) { return _search(list, start, mid, isGreater, searchable); } else { return _search(list, mid+1, end, isGreater, searchable); } }
public List<K> sort(final List<K> input, final BiPredicate<K, K> isGreater) { int sortedResult = isSorted(input, isGreater); if (sortedResult == 1) return input; if (sortedResult == -1) { Collections.reverse(input); return input; } for(int i=1; i<input.size(); i++) { for(int j=0; j<i; j++) { if(isGreater.test(input.get(j), input.get(i))) { input.add(j, input.get(i)); input.remove(i+1); } } } return input; }
@Override public List<K> sort(final List<K> input, final BiPredicate<K, K> isGreater) { int sortedResult = isSorted(input, isGreater); if (sortedResult == 1) return input; if (sortedResult == -1) { Collections.reverse(input); return input; } final Future<List<K>> future = threadPool.submit(new SorterThread<>(input, isGreater, threadPool, 1)); try { return future.get(); } catch(final Exception ex) { throw new RuntimeException(ex); } }
public void testToImmutableSortedMultiset() { BiPredicate<ImmutableSortedMultiset<String>, ImmutableSortedMultiset<String>> equivalence = (ms1, ms2) -> ms1.equals(ms2) && ms1.entrySet().asList().equals(ms2.entrySet().asList()) && ms1.comparator().equals(ms2.comparator()); CollectorTester.of( ImmutableSortedMultiset.<String>toImmutableSortedMultiset( String.CASE_INSENSITIVE_ORDER), equivalence) .expectCollects(ImmutableSortedMultiset.emptyMultiset(String.CASE_INSENSITIVE_ORDER)) .expectCollects( ImmutableSortedMultiset.orderedBy(String.CASE_INSENSITIVE_ORDER) .addCopies("a", 2) .addCopies("b", 1) .addCopies("c", 3) .build(), "a", "c", "b", "c", "A", "C"); }
@Test public void testCaptureArrayList() { BiPredicate<Integer, Integer> biPredicate; if (System.currentTimeMillis() > 5) { // Always uses this branch String data2 = optimisationBarrier(rawCityData); ArrayList<CountryData> cities = CountryData.parseCityData(data2); biPredicate = (i, e) -> cities.get(i).getPopulation() == e; } else { biPredicate = (i, e) -> i == e; } System.gc(); assertTrue(biPredicate.test(0, 20693000)); // China assertTrue(biPredicate.test(16, 3040740)); // Ethiopia assertFalse(biPredicate.test(3, 24)); // Japan }
boolean removeIf(BiPredicate<? super K, ? super V> filter) { checkNotNull(filter); boolean changed = false; for (K key : keySet()) { while (true) { V value = get(key); if (value == null || !filter.test(key, value)) { break; } else if (LocalCache.this.remove(key, value)) { changed = true; break; } } } return changed; }
public void testToImmutableListMultimap() { Collector<Entry<String, Integer>, ?, ImmutableListMultimap<String, Integer>> collector = ImmutableListMultimap.toImmutableListMultimap(Entry::getKey, Entry::getValue); BiPredicate<ImmutableListMultimap<?, ?>, ImmutableListMultimap<?, ?>> equivalence = Equivalence.equals() .onResultOf((ImmutableListMultimap<?, ?> mm) -> mm.asMap().entrySet().asList()) .and(Equivalence.equals()); CollectorTester.of(collector, equivalence) .expectCollects(ImmutableListMultimap.of()) .expectCollects( ImmutableListMultimap.of("a", 1, "b", 2, "a", 3, "c", 4), mapEntry("a", 1), mapEntry("b", 2), mapEntry("a", 3), mapEntry("c", 4)); }
public void testFlatteningToImmutableSetMultimap() { Collector<String, ?, ImmutableSetMultimap<Character, Character>> collector = ImmutableSetMultimap.flatteningToImmutableSetMultimap( str -> str.charAt(0), str -> str.substring(1).chars().mapToObj(c -> (char) c)); BiPredicate<Multimap<?, ?>, Multimap<?, ?>> equivalence = Equivalence.equals() .onResultOf((Multimap<?, ?> mm) -> ImmutableList.copyOf(mm.asMap().entrySet())) .and(Equivalence.equals()); ImmutableSetMultimap<Character, Character> empty = ImmutableSetMultimap.of(); ImmutableSetMultimap<Character, Character> filled = ImmutableSetMultimap.<Character, Character>builder() .putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')) .putAll('a', Arrays.asList('p', 'p', 'l', 'e')) .putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')) .putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')) .putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')) .build(); CollectorTester.of(collector, equivalence) .expectCollects(empty) .expectCollects(filled, "banana", "apple", "carrot", "asparagus", "cherry"); }
public void testFlatteningToMultimap() { Collector<String, ?, ListMultimap<Character, Character>> collector = Multimaps.flatteningToMultimap( str -> str.charAt(0), str -> str.substring(1).chars().mapToObj(c -> (char) c), MultimapBuilder.linkedHashKeys().arrayListValues()::build); BiPredicate<Multimap<?, ?>, Multimap<?, ?>> equivalence = Equivalence.equals() .onResultOf((Multimap<?, ?> mm) -> ImmutableList.copyOf(mm.asMap().entrySet())) .and(Equivalence.equals()); ListMultimap<Character, Character> empty = MultimapBuilder.linkedHashKeys().arrayListValues().build(); ListMultimap<Character, Character> filled = MultimapBuilder.linkedHashKeys().arrayListValues().build(); filled.putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')); filled.putAll('a', Arrays.asList('p', 'p', 'l', 'e')); filled.putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')); filled.putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')); filled.putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')); CollectorTester.of(collector, equivalence) .expectCollects(empty) .expectCollects(filled, "banana", "apple", "carrot", "asparagus", "cherry"); }
public static void demo2_API() { Traffic api = new TrafficImpl(Month.APRIL, DayOfWeek.FRIDAY, 17, "USA", "Denver", "Main103S"); double timeSec = 10.0; int trafficUnitsNumber = 10; api.speedAfterStart(timeSec, trafficUnitsNumber); SpeedModel speedModel = (t, wp, hp) -> { double weightPower = 2.0 * hp * 746 * 32.174 / wp; return Math.round(Math.sqrt(t * weightPower) * 0.68); }; api.speedAfterStart(timeSec, trafficUnitsNumber, speedModel); Predicate<TrafficUnit> limitTraffic = tu -> (tu.getHorsePower() < 250 && tu.getVehicleType() == Vehicle.VehicleType.CAR) || (tu.getHorsePower() < 400 && tu.getVehicleType() == Vehicle.VehicleType.TRUCK); Predicate<TrafficUnit> limitTraffic2 = tu -> tu.getRoadCondition() == RoadCondition.WET && tu.getTireCondition() == SpeedModel.TireCondition.NEW && tu.getTemperature() > 65; api.speedAfterStart(timeSec, trafficUnitsNumber, speedModel, limitTraffic); BiPredicate<TrafficUnit, Double> limitTrafficAndSpeed = (tu, sp) -> (sp > (tu.getSpeedLimitMph() + 8.0) && tu.getRoadCondition() == RoadCondition.DRY) || (sp > (tu.getSpeedLimitMph() + 5.0) && tu.getRoadCondition() == RoadCondition.WET) || (sp > (tu.getSpeedLimitMph() + 0.0) && tu.getRoadCondition() == RoadCondition.SNOW); api.speedAfterStart(timeSec, trafficUnitsNumber, speedModel, limitTrafficAndSpeed); BiConsumer<TrafficUnit, Double> printResults = (tm, sp) -> System.out.println("Road " + tm.getRoadCondition() + ", tires " + tm.getTireCondition() + ": " + tm.getVehicleType().getType() + " speedMph (" + timeSec + " sec)=" + sp + " mph"); api.speedAfterStart(timeSec, trafficUnitsNumber, speedModel, limitTrafficAndSpeed, printResults); }
private BiPredicate<Path, BasicFileAttributes> nameMatchesModule(List<CarnotzetModule> modules) { return (filePath, fileAttr) -> { Path fileName = filePath.getFileName(); if (fileName == null) { // Should not happen return false; } return modules.stream().anyMatch(m -> m.getServiceId().equals(fileName.toString()) || m.getName().equals(fileName.toString())); }; }
public void speedAfterStart(double timeSec, int trafficUnitsNumber, SpeedModel speedModel, BiPredicate<TrafficUnit, Double> limitSpeed, BiConsumer<TrafficUnit, Double> printResult) { List<TrafficUnit> trafficUnits = FactoryTraffic.generateTraffic(trafficUnitsNumber, month, dayOfWeek, hour, country, city, trafficLight); for(TrafficUnit tu: trafficUnits){ Vehicle vehicle = FactoryVehicle.build(tu); vehicle.setSpeedModel(speedModel); double speed = vehicle.getSpeedMph(timeSec); speed = Math.round(speed * tu.getTraction()); if(limitSpeed.test(tu, speed)){ printResult.accept(tu, speed); } } }
public void testToImmutableSortedSet_customComparator() { Collector<String, ?, ImmutableSortedSet<String>> collector = ImmutableSortedSet.toImmutableSortedSet(String.CASE_INSENSITIVE_ORDER); BiPredicate<ImmutableSortedSet<String>, ImmutableSortedSet<String>> equivalence = (set1, set2) -> set1.equals(set2) && set1.asList().equals(set2.asList()) && set1.comparator().equals(set2.comparator()); ImmutableSortedSet<String> expected = ImmutableSortedSet.orderedBy(String.CASE_INSENSITIVE_ORDER) .add("a", "B", "c", "d") .build(); CollectorTester.of(collector, equivalence) .expectCollects(expected, "a", "B", "a", "c", "b", "b", "d"); }
@Override public void update(T entity, BiPredicate<String, Object> includeColumnPredicate) { callBeforeUpdate(entity); Map<String, Object> values = EntityUtils.values(entity, domainClass, true); if (includeColumnPredicate != null) { values = filterMap(values, includeColumnPredicate); } SimpleJdbcUpdate jdbcUpdate = SimpleJdbcUpdate.create(operations(), domainClass); jdbcUpdate.update(values); callAfterUpdate(entity); }
@SuppressWarnings("unchecked") HelperEventListener(SingleBuilder<T> builder, List<BiConsumer<SingleSubscription<T>, ? super T>> handlers) { this.eventClass = builder.eventClass; this.priority = builder.priority; this.exceptionConsumer = builder.exceptionConsumer; this.filters = builder.filters.toArray(new Predicate[builder.filters.size()]); this.preExpiryTests = builder.preExpiryTests.toArray(new BiPredicate[builder.preExpiryTests.size()]); this.midExpiryTests = builder.midExpiryTests.toArray(new BiPredicate[builder.midExpiryTests.size()]); this.postExpiryTests = builder.postExpiryTests.toArray(new BiPredicate[builder.postExpiryTests.size()]); this.handlers = handlers.toArray(new BiConsumer[handlers.size()]); this.timing = Timings.of("helper-events: " + handlers.stream().map(handler -> Delegate.resolve(handler).getClass().getName()).collect(Collectors.joining(" | "))); }
public JsonArrayMatcher(T vnetEntityValue, Function<T, String> getKey1, BiPredicate<T, JsonObject> checkKey1, List<String> jsonFieldNames1, BiFunction<T, String, String> getValue1) { vnetEntity = vnetEntityValue; getKey = getKey1; checkKey = checkKey1; jsonFieldNames = jsonFieldNames1; getValue = getValue1; }
private InstancePut findProtoFieldWrite(BasicBlock block, DexType instanceType, BiPredicate<DexField, DexType> filter, DominatorTree dom) { for (BasicBlock current : dom.dominatedBlocks(block)) { InstructionIterator insns = current.iterator(); InstancePut instancePut = (InstancePut) insns.nextUntil(Instruction::isInstancePut); if (instancePut != null && filter.test(instancePut.getField(), instanceType)) { return instancePut; } } return null; }
@Override public boolean equals(Instruction other, BiPredicate<IndexedDexItem, IndexedDexItem> equality) { if (other == null || (this.getClass() != other.getClass())) { return false; } Format35c o = (Format35c) other; return o.A == A && o.C == C && o.D == D && o.E == E && o.F == F && o.G == G && equality.test(BBBB, o.BBBB); }
@Override public boolean equals(Instruction other, BiPredicate<IndexedDexItem, IndexedDexItem> equality) { if (other == null || this.getClass() != other.getClass()) { return false; } Format21c o = (Format21c) other; return o.AA == AA && equality.test(BBBB, o.BBBB); }
@Override public boolean equals(Instruction other, BiPredicate<IndexedDexItem, IndexedDexItem> equality) { if (other == null || (this.getClass() != other.getClass())) { return false; } Format4rcc o = (Format4rcc) other; return o.AA == AA && o.CCCC == CCCC && equality.test(BBBB, o.BBBB) && equality.test(HHHH, o.HHHH); }
@Override public boolean equals(Instruction other, BiPredicate<IndexedDexItem, IndexedDexItem> equality) { if (other == null || this.getClass() != other.getClass()) { return false; } Format22c o = (Format22c) other; return o.A == A && o.B == B && equality.test(CCCC, o.CCCC); }
@Override public boolean equals(Instruction other, BiPredicate<IndexedDexItem, IndexedDexItem> equality) { if (other == null || (this.getClass() != other.getClass())) { return false; } Format31c o = (Format31c) other; return o.AA == AA && equality.test(BBBBBBBB, o.BBBBBBBB); }
/** * Used to determine if the given predicate is valid (i.e. returns true for all items in this map). */ public static <K,V> boolean every(Map<K,V> receiver, BiPredicate<K,V> predicate) { for (Map.Entry<K,V> kvPair : receiver.entrySet()) { if (predicate.test(kvPair.getKey(), kvPair.getValue()) == false) { return false; } } return true; }
/** * Finds the first entry matching the predicate, or returns null. */ public static <K,V> Map.Entry<K,V> find(Map<K,V> receiver, BiPredicate<K,V> predicate) { for (Map.Entry<K,V> kvPair : receiver.entrySet()) { if (predicate.test(kvPair.getKey(), kvPair.getValue())) { return kvPair; } } return null; }
private Decision doDecide(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation, BiPredicate<Integer, Integer> decider) { IndexMetaData indexMd = allocation.metaData().getIndexSafe(shardRouting.index()); final int indexShardLimit = INDEX_TOTAL_SHARDS_PER_NODE_SETTING.get(indexMd.getSettings(), settings); // Capture the limit here in case it changes during this method's // execution final int clusterShardLimit = this.clusterShardLimit; if (indexShardLimit <= 0 && clusterShardLimit <= 0) { return allocation.decision(Decision.YES, NAME, "total shard limits are disabled: [index: %d, cluster: %d] <= 0", indexShardLimit, clusterShardLimit); } int indexShardCount = 0; int nodeShardCount = 0; for (ShardRouting nodeShard : node) { // don't count relocating shards... if (nodeShard.relocating()) { continue; } nodeShardCount++; if (nodeShard.index().equals(shardRouting.index())) { indexShardCount++; } } if (clusterShardLimit > 0 && decider.test(nodeShardCount, clusterShardLimit)) { return allocation.decision(Decision.NO, NAME, "too many shards [%d] allocated to this node, cluster setting [%s=%d]", nodeShardCount, CLUSTER_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), clusterShardLimit); } if (indexShardLimit > 0 && decider.test(indexShardCount, indexShardLimit)) { return allocation.decision(Decision.NO, NAME, "too many shards [%d] allocated to this node for index [%s], index setting [%s=%d]", indexShardCount, shardRouting.getIndexName(), INDEX_TOTAL_SHARDS_PER_NODE_SETTING.getKey(), indexShardLimit); } return allocation.decision(Decision.YES, NAME, "the shard count [%d] for this node is under the index limit [%d] and cluster level node limit [%d]", nodeShardCount, indexShardLimit, clusterShardLimit); }
@Override public int search(final List<K> list, final int start, final int end, final K searchable, final BiPredicate<K,K> isGreater) { for(int i=start; i<=end; i++) { if(list.get(i).equals(searchable)) return i; } return -1; }
@Override public List<K> sort(final List<K> input, final BiPredicate<K, K> isGreater) { int sortedResult = isSorted(input, isGreater); if (sortedResult == 1) return input; if (sortedResult == -1) { Collections.reverse(input); return input; } _sort(input, 0, input.size() - 1, isGreater); return input; }
private void _sort(final List<K> input, final int start, final int end, final BiPredicate<K,K> isGreater) { if (start >= end) return; final int pivotLocation = partition(input, start, end, isGreater); // Since we didn't have to change anything to the pivot location, _sort(input, start, pivotLocation - 1, isGreater); _sort(input, pivotLocation + 1, end, isGreater); }
public List<K> sort(final List<K> input, final BiPredicate<K, K> isGreater) { int sortedResult = isSorted(input, isGreater); if (sortedResult == 1) return input; if (sortedResult == -1) { Collections.reverse(input); return input; } final int size = input.size(); // Pick one number at a time for (int i=0; i<size; i++) { // Compare with every other number for(int j=i+1; j<size; j++) { // Replace if we find a smaller number in later place if(isGreater.test(input.get(i), input.get(j))) { final K temp = input.get(i); input.set(i, input.get(j)); input.set(j, temp); } } } return input; }
/** * Collect types into a new closure (using a @code{ClosureHolder}) */ public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) { return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip), ClosureHolder::add, ClosureHolder::merge, ClosureHolder::closure); }