Java Code Examples for java.util.Comparator

The following are top voted examples for showing how to use java.util.Comparator. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: SAPManagerPack   File: ItemUtils.java View source code 6 votes vote down vote up
/**
 * Compares the two given stacks and checks for their equality.<br>
 * <p>They are considered equal if either:
 * <ul>
 * <li>They are both null: Either the instances themselves or their items are both [email protected] null}</li>
 * <li>They have the same item instance and:
 * <ul>
 * <li>If the given comparator is either null or its [email protected] .compare(nbt1, nbt2)} method returns 0</li>
 * <li>Their damage value is the same <i>or</i> either of their damage value has the value of [email protected] OreDictionary#WILDCARD_VALUE}</li>
 * </ul>
 * </li>
 * </ul>
 * </p>
 *
 * @param is1      the first stack
 * @param is2      the second stack
 * @param nbtCheck A comparator for the NBTs of those 2 stacks, can be null to avoid checking for NBT
 * @return true, if the stacks are equal, false otherwise.
 */
public static boolean areStacksEqual(ItemStack is1, ItemStack is2, Comparator<NBTTagCompound> nbtCheck) {
    if( is1 == null || is2 == null ) {
        return is1 == is2;
    }

    if( is1.getItem() == null || is2.getItem() == null ) {
        return is1.getItem() == is2.getItem();
    }

    if( is1.getItem() == is2.getItem() ) {
        if( nbtCheck != null ) {
            if( nbtCheck.compare(is1.getTagCompound(), is2.getTagCompound()) != 0 ) {
                return false;
            }
        }

        return is1.getItemDamage() == OreDictionary.WILDCARD_VALUE || is2.getItemDamage() == OreDictionary.WILDCARD_VALUE
                || is1.getItemDamage() == is2.getItemDamage();
    }

    return false;
}
 
Example 2
Project: The-Digital-Parrot   File: RestrictToChainFilter.java View source code 6 votes vote down vote up
public boolean sameChain(Chain chain) {
	List<ChainLink> chainLinks = chain.getLinks();
	if (chainLinks.size() != links.size()) {
		return false;
	}
	Comparator<ChainLink> comp = ChainLink.getCloneComparator();
	for (int i = 0; i < links.size(); i++) {
		ChainLink filterLink = links.get(i);
		ChainLink chainLink = chainLinks.get(i);
		if (comp.compare(filterLink, chainLink) != 0) {
			// found a pair that's not same
			return false;
		}
	}
	// if we get here, we never found one pair of links that doesn't match
	// -> they all match
	return true;
}
 
Example 3
Project: richfaces   File: ArrangeableModel.java View source code 6 votes vote down vote up
private int compare(FacesContext context, Object rowKey1, Object rowKey2) {
    originalModel.setRowKey(rowKey1);
    Object object1 = originalModel.getRowData();
    originalModel.setRowKey(rowKey2);
    Object object2 = originalModel.getRowData();
    int result = 0;
    for (Iterator<SortField> iterator = state.getSortFields().iterator(); iterator.hasNext() && result == 0;) {
        SortField sortField = iterator.next();
        SortOrder sortOrder = sortField.getSortOrder();
        if (sortOrder != null && !SortOrder.unsorted.equals(sortOrder)) {
            Comparator comparator = sortField.getComparator();
            if (comparator != null) {
                result = comparator.compare(object1, object2);
            } else {
                ValueExpression sortBy = sortField.getSortBy();
                if (sortBy != null) {
                    updateVar(context, var, object1);
                    Object value1 = sortBy.getValue(context.getELContext());
                    updateVar(context, var, object2);
                    Object value2 = sortBy.getValue(context.getELContext());
                    result = compareSortByValues(context, value1, value2);
                }
            }
            if (SortOrder.descending.equals(sortOrder)) {
                result = -result;
            }
        }
    }
    return result;
}
 
Example 4
Project: jlibs   File: ChainedComparator.java View source code 6 votes vote down vote up
@Override
public int compare(T o1, T o2){
    for(Comparator<T> delegate: delegates){
        int result = delegate.compare(o1, o2);
        if(result!=0)
            return result;
    }
    return 0;
}
 
Example 5
Project: breakout   File: CollectionUtils.java View source code 6 votes vote down vote up
public static <T> void testComparator( List<? extends T> list , Comparator<T> comparator )
{
	for( int i = 0 ; i < list.size( ) ; i++ )
	{
		for( int j = i ; j < list.size( ) ; j++ )
		{
			T oi = list.get( i );
			T oj = list.get( j );

			int ci = comparator.compare( oi , oj );
			int cj = comparator.compare( oj , oi );

			if( Math.signum( ci ) != -Math.signum( cj ) )
			{
				throw new RuntimeException( "Bad comparator: " + comparator + "\n\tlist.get(" + i + "): " + oi
					+ "\n\tlist.get(" + j + "): " + oj
					+ "\ncompare(list.get(" + i + "), list.get(" + j + ")): " + ci
					+ "\ncompare(list.get(" + j + "), list.get(" + i + ")): " + cj );
			}
		}
	}
}
 
Example 6
Project: jena   File: QueryIterTopN.java View source code 6 votes vote down vote up
private Iterator<Binding> sortTopN(final QueryIterator qIter, final Comparator<Binding> comparator) {
    return new IteratorDelayedInitialization<Binding>() {
        @Override
        protected Iterator<Binding> initializeIterator() {
            while ( qIter.hasNext() ) {
                Binding binding = qIter.next() ;
                if ( heap.size() < limit )
                    add(binding) ;
                else {
                    Binding currentMaxLeastN = heap.peek() ;
                    if ( comparator.compare(binding, currentMaxLeastN) < 0 )
                        add(binding) ;
                }
            }
            qIter.close() ;
            Binding[] y = heap.toArray(new Binding[]{}) ;
            heap = null ;
            Arrays.sort(y, comparator) ;
            return asList(y).iterator() ;
        }
    } ;
}
 
Example 7
Project: wampspring   File: DestinationPatternsMessageCondition.java View source code 6 votes vote down vote up
/**
 * Compare the two conditions based on the destination patterns they contain. Patterns
 * are compared one at a time, from top to bottom via
 * [email protected] org.springframework.util.PathMatcher#getPatternComparator(String)}. If all
 * compared patterns match equally, but one instance has more patterns, it is
 * considered a closer match.
 * <p>
 * It is assumed that both instances have been obtained via
 * [email protected] #getMatchingCondition(Message)} to ensure they contain only patterns that
 * match the request and are sorted with the best matches on top.
 */
@Override
public int compareTo(DestinationPatternsMessageCondition other, Message<?> message) {
	WampMessage wampMessage = (WampMessage) message;
	String destination = wampMessage.getDestination();

	Comparator<String> patternComparator = this.pathMatcher
			.getPatternComparator(destination);

	Iterator<String> iterator = this.patterns.iterator();
	Iterator<String> iteratorOther = other.patterns.iterator();
	while (iterator.hasNext() && iteratorOther.hasNext()) {
		int result = patternComparator.compare(iterator.next(), iteratorOther.next());
		if (result != 0) {
			return result;
		}
	}
	if (iterator.hasNext()) {
		return -1;
	}
	else if (iteratorOther.hasNext()) {
		return 1;
	}
	else {
		return 0;
	}
}
 
Example 8
Project: extFM-Tooling   File: PermissionComparatorTest.java View source code 6 votes vote down vote up
@Test
public void compareSetAttributesOfDiffFeatures() {
   Comparator<Permission> permissionComparator = new PermissionComparator();
   Feature f5 = getFeature("f5");
   Attribute f5a1 = getAttribute(f5, "a1");

   Feature f6 = getFeature("f6");
   Attribute f6a1 = getAttribute(f6, "a1");
   AttributeOperation as1 = createSetAttribute(f5, f5a1);
   AttributeOperation as2 = createSetAttribute(f6, f6a1);

   int equal = permissionComparator.compare(as1, as2);
   assertEquals(-1, equal);
}
 
Example 9
Project: genome-weaver-align   File: MergeSort.java View source code 6 votes vote down vote up
static <T> void mergeSort(T[] dest, T[] src, int low, int high, int off, Comparator<T> comparator) {

        int length = high - low;
        // Insertion sort on smallest arrays
        if (length < INSERTIONSORT_THRESHOLD) {
            for (int i = low; i < high; i++)
                for (int j = i; j > low && comparator.compare(dest[j - 1], dest[j]) > 0; j--) {
                    swap(dest, j - 1, j);
                }
            return;
        }

        // Recursively sort halves of dest into src
        int destLow = low;
        int destHigh = high;
        low += off;
        high += off;
        int mid = (low + high) >>> 1;
        mergeSort(dest, src, low, mid, -off, comparator);
        mergeSort(dest, src, mid, high, -off, comparator);

        // If list is already sorted, just copy from src to dest.  This is an
        // optimization that results in faster sorts for nearly ordered lists.
        if (comparator.compare(src[mid - 1], src[mid]) <= 0) {
            System.arraycopy(src, low, dest, destLow, length);
            return;
        }

        // Merge sorted halves (now in src) into dest
        for (int i = destLow, p = low, q = mid; i < destHigh; i++) {
            if (q >= high || p < mid && comparator.compare(src[p], src[q]) <= 0)
                dest[i] = src[p++];
            else
                dest[i] = src[q++];
        }

    }
 
Example 10
Project: wpcleaner   File: CompositeComparator.java View source code 6 votes vote down vote up
@Override
public int compare(T o1, T o2) {
  if (comparators != null) {
    Iterator<NamedComparator<T>> itComparator = comparators.iterator();
    Iterator<Boolean> itBoolean = (orders != null) ? orders.iterator() : null;
    while (itComparator.hasNext()) {
      Comparator<T> c = itComparator.next();
      Boolean order = ((itBoolean != null) && (itBoolean.hasNext())) ? itBoolean.next() : Boolean.TRUE;
      int result = c.compare(o1, o2);
      //System.out.println("Comparing [" + o1 + "] and [" + o2 + "] by " + c + ": " + result);
      if (result != 0) {
        return (Boolean.FALSE.equals(order) ? -1 : 1) * result;
      }
    }
  }
  return 0;
}
 
Example 11
Project: closure-stylesheets   File: UnsafeMergeRulesetNodes.java View source code 6 votes vote down vote up
/**
 * Create a comparator for iterables that compares element pairwise using the
 * given element comparator.
 */
private static <T> Comparator<Iterable<? extends T>> createIterableComparator(
    final Comparator<T> elementComparator) {
  return new Comparator<Iterable<? extends T>>() {
    @Override
    public int compare(Iterable<? extends T> o1, Iterable<? extends T> o2) {
      Iterator<? extends T> i1 = o1.iterator();
      Iterator<? extends T> i2 = o2.iterator();
      while (true) {
        if (i1.hasNext() && !i2.hasNext()) {
          return 1;
        } else if (!i1.hasNext() && i2.hasNext()) {
          return -1;
        } else if (!i1.hasNext() && !i2.hasNext()) {
          return 0;
        } else {
          int c = elementComparator.compare(i1.next(), i2.next());
          if (c != 0) {
            return c;
          }
        }
      }
    }
  };
}
 
Example 12
Project: dove   File: ImmutableSortedMap.java View source code 6 votes vote down vote up
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
    Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {
  boolean sameComparator = false;
  if (map instanceof SortedMap) {
    SortedMap<?, ?> sortedMap = (SortedMap<?, ?>) map;
    Comparator<?> comparator2 = sortedMap.comparator();
    sameComparator = (comparator2 == null)
        ? comparator == NATURAL_ORDER
        : comparator.equals(comparator2);
  }

  if (sameComparator && (map instanceof ImmutableSortedMap)) {
    // TODO: Prove that this cast is safe, even though
    // Collections.unmodifiableSortedMap requires the same key type.
    @SuppressWarnings("unchecked")
    ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
    return kvMap;
  }

  // Using List to support concurrent map whose size changes
  List<Entry<?, ?>> list = Lists.newArrayListWithCapacity(map.size());
  for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
    list.add(entryOf(entry.getKey(), entry.getValue()));
  }
  Entry<?, ?>[] entryArray = list.toArray(new Entry<?, ?>[list.size()]);

  if (!sameComparator) {
    sortEntries(entryArray, comparator);
    validateEntries(entryArray, comparator);
  }

  return new ImmutableSortedMap<K, V>(entryArray, comparator);
}
 
Example 13
Project: ClusterBasedRelevanceFeedback   File: MultiTerms.java View source code 6 votes vote down vote up
public MultiTerms(Terms[] subs, ReaderUtil.Slice[] subSlices) throws IOException {
  this.subs = subs;
  this.subSlices = subSlices;
  
  Comparator<BytesRef> _termComp = null;
  for(int i=0;i<subs.length;i++) {
    if (_termComp == null) {
      _termComp = subs[i].getComparator();
    } else {
      // We cannot merge sub-readers that have
      // different TermComps
      final Comparator<BytesRef> subTermComp = subs[i].getComparator();
      if (subTermComp != null && !subTermComp.equals(_termComp)) {
        throw new IllegalStateException("sub-readers have different BytesRef.Comparators; cannot merge");
      }
    }
  }

  termComp = _termComp;
}
 
Example 14
Project: datavalve   File: InMemoryDataProvider.java View source code 6 votes vote down vote up
private void defineOrdering(String key) {
	if (key == null) {
		activeSortOrder = null;
		return;
	}

	Comparator<T> sorter = translateOrderKey(key);

	// if there is no matching sort order, just clear it and leave the order
	// as is.
	if (sorter == null) {
		activeSortOrder = null;
		return;
	}

	// return if we are already sorted by this value then do nothing
	if (sorter.equals(activeSortOrder)) {
		return;
	}
	// when we changed the order, it defaults to ascending
	// orderedAscendingFlag = true;
	activeSortOrder = sorter;
	// sort();
}
 
Example 15
Project: Valkyrie-RCP   File: AbstractListBinding.java View source code 6 votes vote down vote up
public void setComparator(Comparator comparator) {
    if (comparator != this.comparator || (comparator != null && !comparator.equals(this.comparator))) {
        if (this.comparator instanceof Observable) {
            ((Observable) this.comparator).deleteObserver(this);
        }
        this.comparator = comparator;
        if (comparator instanceof Observable) {
            ((Observable) this.comparator).addObserver(this);
        }
        update();
    }
}
 
Example 16
Project: guava-experimental   File: ImmutableSortedMap.java View source code 6 votes vote down vote up
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
    Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {

  if (map instanceof ImmutableSortedMap) {
    // TODO: Prove that this cast is safe, even though
    // Collections.unmodifiableSortedMap requires the same key type.
    @SuppressWarnings("unchecked")
    ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
    Comparator<?> comparator2 = kvMap.comparator();
    boolean sameComparator = (comparator2 == null)
        ? comparator == NATURAL_ORDER
        : comparator.equals(comparator2);
    if (sameComparator) {
      return kvMap;
    }
  }

  SortedMap<K, V> delegate = newModifiableDelegate(comparator);
  for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
    putEntryWithChecks(delegate, entry);
  }
  return newView(unmodifiableSortedMap(delegate), comparator);
}
 
Example 17
Project: jnlp   File: SortedIterables.java View source code 6 votes vote down vote up
/**
 * Returns [email protected] true} if [email protected] elements} is a sorted collection using an ordering equivalent
 * to [email protected] comparator}.
 */
public static boolean hasSameComparator(Comparator<?> comparator, Iterable<?> elements) {
  checkNotNull(comparator);
  checkNotNull(elements);
  Comparator<?> comparator2;
  if (elements instanceof SortedSet) {
    comparator2 = comparator((SortedSet<?>) elements);
  } else if (elements instanceof SortedIterable) {
    comparator2 = ((SortedIterable<?>) elements).comparator();
  } else {
    return false;
  }
  return comparator.equals(comparator2);
}
 
Example 18
Project: guava   File: ImmutableSortedMap.java View source code 6 votes vote down vote up
private static <K, V> ImmutableSortedMap<K, V> copyOfInternal(
    Map<? extends K, ? extends V> map, Comparator<? super K> comparator) {

  if (map instanceof ImmutableSortedMap) {
    // TODO: Prove that this cast is safe, even though
    // Collections.unmodifiableSortedMap requires the same key type.
    @SuppressWarnings("unchecked")
    ImmutableSortedMap<K, V> kvMap = (ImmutableSortedMap<K, V>) map;
    Comparator<?> comparator2 = kvMap.comparator();
    boolean sameComparator = (comparator2 == null)
        ? comparator == NATURAL_ORDER
        : comparator.equals(comparator2);
    if (sameComparator) {
      return kvMap;
    }
  }

  SortedMap<K, V> delegate = newModifiableDelegate(comparator);
  for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
    putEntryWithChecks(delegate, entry);
  }
  return newView(unmodifiableSortedMap(delegate), comparator);
}
 
Example 19
Project: parkandrideAPI   File: ValidationException.java View source code 6 votes vote down vote up
private static String formatViolations(Iterable<Violation> violations) {
    StringJoiner joiner = new StringJoiner(", ");
    StreamSupport.stream(violations.spliterator(), false)
            .sorted(Comparator.comparing((Violation v) -> v.path).thenComparing(v -> v.type))
            .forEach(v -> joiner.add(v.path + " (" + v.type + ")"));
    return joiner.toString();
}
 
Example 20
Project: expenditures   File: MissionResponsibilityController.java View source code 6 votes vote down vote up
private void findAllUnits(JsonArray result, String[] input) {
    Stream<Party> stream = Bennu.getInstance().getPartiesSet().stream();
    Supplier<TreeSet<Party>> s = () -> new TreeSet<Party>(Comparator.comparing(u -> u.getPresentationName()));
    stream.filter(p -> p.isUnit() && hasMatch(input, StringNormalizer.normalize(p.getPresentationName()).toLowerCase()))
            .collect(Collectors.toCollection(s)).forEach(u -> addToJson(result, u));

}
 
Example 21
Project: rsimulator   File: FileUtilsImpl.java View source code 6 votes vote down vote up
public List<Path> findRequests(Path path, String extension) {
    List<Path> requests;

    try (Stream<Path> stream = Files.walk(path)) {
        Predicate<Path> predicate = p -> Files.isRegularFile(p) && p.toFile().getName().endsWith(SUFFIX_PREFIX.concat(extension));
        requests = stream.filter(predicate).collect(Collectors.toList());
        Collections.sort(requests, Comparator.comparing(Path::getNameCount).thenComparing(Path::compareTo)); // Do not want depth first as given by Files.walk
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    log.debug("Requests: {}", requests);
    return requests;
}
 
Example 22
Project: streamex   File: MoreCollectorsTest.java View source code 6 votes vote down vote up
@Test
public void testGreatest() {
    List<Integer> ints = IntStreamEx.of(new Random(1), 1000, 1, 1000).boxed().toList();
    List<Integer> sorted = StreamEx.of(ints).sorted().toList();
    List<Integer> revSorted = StreamEx.of(ints).reverseSorted().toList();
    Comparator<Integer> byString = Comparator.comparing(String::valueOf);
    checkShortCircuitCollector("least(0)", Collections.emptyList(), 0, ints::stream, MoreCollectors.least(0));
    checkCollector("least(5)", sorted.subList(0, 5), ints::stream, MoreCollectors.least(5));
    checkCollector("least(20)", sorted.subList(0, 20), ints::stream, MoreCollectors.least(20));
    checkCollector("least(MAX)", sorted, ints::stream, MoreCollectors.least(Integer.MAX_VALUE));
    checkCollector("least(byString, 20)", StreamEx.of(ints).sorted(byString).limit(20).toList(), ints::stream,
        MoreCollectors.least(byString, 20));

    checkShortCircuitCollector("greatest(0)", Collections.emptyList(), 0, ints::stream, MoreCollectors.greatest(0));
    checkCollector("greatest(5)", revSorted.subList(0, 5), ints::stream, MoreCollectors.greatest(5));
    checkCollector("greatest(20)", revSorted.subList(0, 20), ints::stream, MoreCollectors.greatest(20));
    checkCollector("greatest(MAX)", revSorted, ints::stream, MoreCollectors.greatest(Integer.MAX_VALUE));
    checkCollector("greatest(byString, 20)", StreamEx.of(ints).reverseSorted(byString).limit(20).toList(),
        ints::stream, MoreCollectors.greatest(byString, 20));

    Supplier<Stream<Integer>> s = () -> IntStreamEx.range(100).boxed();
    checkCollector("1", IntStreamEx.range(1).boxed().toList(), s, MoreCollectors.least(1));
    checkCollector("2", IntStreamEx.range(2).boxed().toList(), s, MoreCollectors.least(2));
    checkCollector("10", IntStreamEx.range(10).boxed().toList(), s, MoreCollectors.least(10));
    checkCollector("100", IntStreamEx.range(100).boxed().toList(), s, MoreCollectors.least(100));
    checkCollector("200", IntStreamEx.range(100).boxed().toList(), s, MoreCollectors.least(200));
}
 
Example 23
Project: polly   File: NewsEntry.java View source code 6 votes vote down vote up
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public int compareTo(NewsEntry o) {
    return Comparator.comparing(NewsEntry::getType)
            .thenComparing(NewsEntry::getCompDate).reversed()
            .thenComparing((n1, n2) -> {
                if (n1.subject instanceof Comparable && 
                        n1.getClass() == n2.getClass()) {
                    return ((Comparable) n1).compareTo(n2);
                }
                return 0;
            })
            .compare(this, o);
}
 
Example 24
Project: Archimulator   File: LFUPolicy.java View source code 6 votes vote down vote up
@Override
public CacheAccess<StateT> handleReplacement(MemoryHierarchyAccess access, int set, int tag) {
    int victimWay = this.mirrorCache.getLines(set).stream()
            .min(Comparator.comparing(mirrorCacheLine -> ((BooleanValueProvider) mirrorCacheLine.getStateProvider()).frequency))
            .get().getWay();

    return new CacheAccess<>(this.getCache(), access, set, victimWay, tag);
}
 
Example 25
Project: jacis   File: JacisExample2.java View source code 6 votes vote down vote up
public static void main(String[] args) {
  JacisContainer container = new JacisContainer();
  JacisObjectTypeSpec<String, Account, Account> objectTypeSpec = new JacisObjectTypeSpec<>(String.class, Account.class, new JacisCloningObjectAdapter<Account>());
  JacisStore<String, Account, Account> store = container.createStore(objectTypeSpec);

  // First we create some accounts to have some test data...

  container.withLocalTx(() -> {
    store.update("account0", new Account("account0").withdraw(100));
    store.update("account1", new Account("account1").deposit(100));
    store.update("account2", new Account("account2").deposit(200));
    store.update("account3", new Account("account3").deposit(300));
    store.update("account4", new Account("account4").deposit(400));
    store.update("account5", new Account("account5").deposit(500));
    store.update("account6", new Account("account6").deposit(600));
    store.update("account7", new Account("account7").deposit(700));
    store.update("account8", new Account("account8").deposit(800));
    store.update("account9", new Account("account9").deposit(900));
  });

  // Now we show some examples how to use the stream API (note read only access is possible without a transaction)
  System.out.println("sum=" + store.streamReadOnly().mapToLong(acc -> acc.getBalance()).sum());
  // starting with a filter
  System.out.println("#>500=" + store.streamReadOnly(acc -> acc.getBalance() > 500).count());
  // adding 10% interest
  container.withLocalTx(() -> {
    store.stream(acc -> acc.getBalance() > 0).forEach(acc -> {
      store.update(acc.getName(), acc.deposit(acc.getBalance() / 10));
    });
  });
  // output all accounts
  String str = store.streamReadOnly().//
      sorted(Comparator.comparing(acc -> acc.getName())). //
      map(acc -> acc.getName() + ":" + acc.getBalance()).//
      collect(Collectors.joining(", "));
  System.out.println("Accounts: " + str);
}
 
Example 26
Project: jease   File: Informatons.java View source code 6 votes vote down vote up
public static Map<Class<?>, Integer> getDatabaseClassCount() {
	Map<Class<?>, Integer> resultMap = new TreeMap<>(
			Comparator.comparing(Class::getName));
	for (Persistent obj : Database.query(Persistent.class)) {
		Class<?> clazz = obj.getClass();
		if (!resultMap.containsKey(clazz)) {
			resultMap.put(clazz, 0);
		}
		resultMap.put(clazz, resultMap.get(clazz) + 1);
	}
	return resultMap;
}
 
Example 27
Project: idnadrev   File: NextTaskChooser.java View source code 6 votes vote down vote up
protected List<Task> sortTasksByPrio(int maxTime, List<Task> allPossibleTasks) {
  log.debug("Got {} tasks to choose from: {}", allPossibleTasks.size(), tasks2NameString(allPossibleTasks));
  allPossibleTasks = new ArrayList<>(allPossibleTasks);

  Collections.sort(allPossibleTasks, Comparator.comparing(task -> {
    long ageInDays = Duration.between(task.getCreationTime(), LocalDateTime.now()).toDays();
    long agePrio = ageInDays * 10;
    long asapPrio = task.getState() == TaskState.ASAP ? 100 : 0;

    long estimatedMinutes = task.getEstimatedTime().toMinutes();

    long matchingTimePrio;
    if (estimatedMinutes > options.getTimeThreshold()) {
      matchingTimePrio = (long) ((maxTime - estimatedMinutes) * 10D / maxTime);
    } else {
      matchingTimePrio = 0;
    }


    agePrio *= options.getAgeFactor();
    asapPrio *= options.getAsapFactor();
    matchingTimePrio *= options.getTimeFactor();
    long totalPrio = agePrio + asapPrio + matchingTimePrio;
    log.debug("Task {} has prio {}", task.getName(), totalPrio);
    return totalPrio;
  }));
  Collections.reverse(allPossibleTasks);
  log.debug("Sorted tasks to the following order: {}", tasks2NameString(allPossibleTasks));
  return allPossibleTasks;
}
 
Example 28
Project: java8examples   File: ComparatorExamples.java View source code 6 votes vote down vote up
public void ascendingAgeThenName() {
	System.out.println("Sort in ascending order by age and then name");		
	System.out.println(people.stream()
			.sorted(Comparator.comparing(byAge)
					.thenComparing(byName))
					.collect(Collectors.toList()));		
}
 
Example 29
Project: keywhiz   File: Printing.java View source code 6 votes vote down vote up
public void printClientWithDetails(Client client, List<String> options) {
  System.out.println(client.getName());
  ClientDetailResponse clientDetails;
  try {
    clientDetails = keywhizClient.clientDetailsForId(client.getId());
  } catch (IOException e) {
    throw Throwables.propagate(e);
  }

  if (options.contains("groups")) {
    System.out.println("\tGroups:");
    clientDetails.groups.stream()
        .sorted(Comparator.comparing(Group::getName))
        .forEach(g -> System.out.println(INDENT + g.getName()));
  }

  if (options.contains("secrets")) {
    System.out.println("\tSecrets:");
    clientDetails.secrets.stream()
        .sorted(Comparator.comparing(SanitizedSecret::name))
        .forEach(s -> System.out.println(INDENT + SanitizedSecret.displayName(s)));
  }
}
 
Example 30
Project: molgenis   File: SemanticSearchServiceImpl.java View source code 6 votes vote down vote up
/**
 * Computes the best matching synonym which is closest to a set of search terms.<br/>
 * Will stem the [email protected] OntologyTerm} 's synonyms and the search terms, and then compute the maximum
 * [email protected] StringDistance} between them. 0 means disjunct, 1 means identical
 * 
 * @param ontologyTerm
 *            the [email protected] OntologyTerm}
 * @param searchTerms
 *            the search terms
 * @return the maximum [email protected] StringDistance} between the ontologyterm and the search terms
 */
public Hit<String> bestMatchingSynonym(OntologyTerm ontologyTerm, Set<String> searchTerms)
{
	Stemmer stemmer = new Stemmer();
	Optional<Hit<String>> bestSynonym = ontologyTerm.getSynonyms().stream()
			.map(synonym -> Hit.<String> create(synonym, distanceFrom(synonym, searchTerms, stemmer)))
			.max(Comparator.naturalOrder());
	return bestSynonym.get();
}
 
Example 31
Project: streamex   File: MoreCollectorsTest.java View source code 6 votes vote down vote up
@Test
public void testMaxAll() {
    List<String> input = Arrays.asList("a", "bb", "c", "", "cc", "eee", "bb", "ddd");
    checkCollector("maxAll", Arrays.asList("eee", "ddd"), input::stream,
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    Collector<String, ?, String> maxAllJoin = MoreCollectors.maxAll(Comparator.comparingInt(String::length),
        Collectors.joining(","));
    checkCollector("maxAllJoin", "eee,ddd", input::stream, maxAllJoin);
    checkCollector("minAll", 1L, input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length), Collectors.counting()));
    checkCollector("minAllEmpty", Arrays.asList(""), input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty("maxAll", Collections.emptyList(),
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty("maxAllJoin", "", maxAllJoin);

    List<Integer> ints = IntStreamEx.of(new Random(1), 10000, 1, 1000).boxed().toList();
    List<Integer> expectedMax = getMaxAll(ints, Comparator.naturalOrder());
    List<Integer> expectedMin = getMaxAll(ints, Comparator.reverseOrder());
    Collector<Integer, ?, SimpleEntry<Integer, Long>> downstream = MoreCollectors.pairing(MoreCollectors.first(),
        Collectors.counting(), (opt, cnt) -> new AbstractMap.SimpleEntry<>(opt.get(), cnt));

    checkCollector("maxAll", expectedMax, ints::stream, MoreCollectors.maxAll(Integer::compare));
    checkCollector("minAll", expectedMin, ints::stream, MoreCollectors.minAll());
    checkCollector("entry", new SimpleEntry<>(expectedMax.get(0), (long) expectedMax.size()), ints::stream,
        MoreCollectors.maxAll(downstream));
    checkCollector("entry", new SimpleEntry<>(expectedMin.get(0), (long) expectedMin.size()), ints::stream,
        MoreCollectors.minAll(downstream));

    Integer a = new Integer(1), b = new Integer(1), c = new Integer(1000), d = new Integer(1000);
    ints = IntStreamEx.range(10, 100).boxed().append(a, c).prepend(b, d).toList();
    for (StreamExSupplier<Integer> supplier : streamEx(ints::stream)) {
        List<Integer> list = supplier.get().collect(MoreCollectors.maxAll());
        assertEquals(2, list.size());
        assertSame(d, list.get(0));
        assertSame(c, list.get(1));

        list = supplier.get().collect(MoreCollectors.minAll());
        assertEquals(2, list.size());
        assertSame(b, list.get(0));
        assertSame(a, list.get(1));
    }
}
 
Example 32
Project: L2J_LoginServer   File: Util.java View source code 6 votes vote down vote up
/**
 * Gets the next or same closest date from the specified days in [email protected] daysOfWeek List} at specified [email protected] hour} and [email protected] min}.
 * @param daysOfWeek the days of week
 * @param hour the hour
 * @param min the min
 * @return the next or same date from the days of week at specified time
 * @throws IllegalArgumentException if the [email protected] daysOfWeek List} is empty.
 */
public static LocalDateTime getNextClosestDateTime(List<DayOfWeek> daysOfWeek, int hour, int min) throws IllegalArgumentException
{
	if (daysOfWeek.isEmpty())
	{
		throw new IllegalArgumentException("daysOfWeek should not be empty.");
	}
	
	final LocalDateTime dateNow = LocalDateTime.now();
	final LocalDateTime dateNowWithDifferentTime = dateNow.withHour(hour).withMinute(min).withSecond(0);
	
	// @formatter:off
	return daysOfWeek.stream()
		.map(d -> dateNowWithDifferentTime.with(TemporalAdjusters.nextOrSame(d)))
		.filter(d -> d.isAfter(dateNow))
		.min(Comparator.naturalOrder())
		.orElse(dateNowWithDifferentTime.with(TemporalAdjusters.next(daysOfWeek.get(0))));
	// @formatter:on
}
 
Example 33
Project: guava-stream   File: MoreCollectors.java View source code 6 votes vote down vote up
public static <T, K extends Comparable<K>, V extends Comparable<V>> Collector<T, ?, ImmutableSetMultimap<K, V>> toImmutableSetMultimapNaturalOrder(
		Function<? super T, ? extends K> keyMapper,
		Function<? super T, ? extends V> valueMapper) {
	return toImmutableMultimap(() -> ImmutableSetMultimap.<K, V>builder()
					.orderKeysBy(Comparator.naturalOrder())
					.orderValuesBy(Comparator.naturalOrder()),
			keyMapper, valueMapper, UNORDERED, CONCURRENT);
}
 
Example 34
Project: Strata   File: Swap.java View source code 6 votes vote down vote up
/**
 * Gets the start date of the swap.
 * <p>
 * This is the earliest accrual date of the legs, often known as the effective date.
 * This date has been adjusted to be a valid business day.
 * 
 * @return the start date of the swap
 */
@DerivedProperty
public LocalDate getStartDate() {
  return legs.stream()
      .map(SwapLeg::getStartDate)
      .min(Comparator.naturalOrder())
      .get();  // always at least one leg, so get() is safe
}
 
Example 35
Project: retrolambda   File: InterfaceStaticMethodsTest.java View source code 6 votes vote down vote up
@Test
public void calling_static_methods_of_library_interfaces__new_method_on_old_interface() {
    assumeThat(SystemUtils.JAVA_VERSION_FLOAT, is(lessThan(1.8f)));

    thrown.expect(IncompatibleClassChangeError.class);
    thrown.expectMessage(SystemUtils.isJavaVersionAtLeast(1.6f)
            ? equalTo("Found interface java.util.Comparator, but class was expected")
            : nullValue(String.class)); // on Java 5 there is no message

    // We don't want this call to prevent loading this whole test class,
    // it should only fail when this line is executed
    Comparator.naturalOrder();
}
 
Example 36
Project: GRire2   File: GlobalRetrievalSystem.java View source code 6 votes vote down vote up
public List<RankedItem> query(String id, String indexName){
    Map<String, float[][]> index=_configuration.getStorer()
            .getMap(indexName + "_" + _configuration.getName() + "_features");
    SimilarityMeasure similarityMeasure = _configuration.getSimilarityMeasure();
    float[][] queryDescriptor = index.get(id);
    return index.entrySet().stream()
            .map(img -> new RankedItem(img.getKey(), similarityMeasure.calculate(queryDescriptor, img.getValue())))
            .sorted(similarityMeasure.getType() == SimilarityMeasure.SimilarityType.DISTANCE ?
                    Comparator.<RankedItem>naturalOrder(): Comparator.<RankedItem>reverseOrder())
            .collect(Collectors.toList());
}
 
Example 37
Project: gs-collections   File: ImmutableEmptySortedBagTest.java View source code 6 votes vote down vote up
@Override
@Test(expected = NoSuchElementException.class)
public void max_without_comparator()
{
    this.classUnderTest().max();
    this.classUnderTest().max(Comparator.<Integer>naturalOrder());
}
 
Example 38
Project: james-core   File: SubsetProblem.java View source code 6 votes vote down vote up
/**
 * <p>
 * Creates a new subset problem with given data, objective and minimum/maximum subset size. Both <code>objective</code>
 * and <code>data</code> are not allowed to be <code>null</code>, an exception will be thrown if they are. Any objective
 * designed to evaluate subset solutions (or more general solutions) using the specified data type (or more general data)
 * is accepted. The minimum and maximum subset size should be contained in <code>[0,n]</code> where <code>n</code>
 * is the number of items in the given data from which a subset is to be selected. Also, the minimum size
 * should be smaller than or equal to the maximum size.
 * </p>
 * <p>
 * If <code>orderIDs</code> is <code>true</code>, subset solutions generated by this problem will order IDs
 * in ascending order (according to the natural integer ordering).
 * </p>
 * 
 * @param data underlying data, can not be <code>null</code>
 * @param objective objective function, can not be <code>null</code>
 * @param minSubsetSize minimum subset size (should be &ge; 0 and &le; maximum subset size)
 * @param maxSubsetSize maximum subset size (should be &ge; minimum subset size and &le; number of items in underlying data)
 * @param orderIDs indicates whether IDs are ordered (ascending) in generated subset solutions
 * 
 * @throws NullPointerException if <code>objective</code> or <code>data</code> is <code>null</code>
 * @throws IllegalArgumentException if an invalid minimum or maximum subset size is specified
 */
public SubsetProblem(DataType data, Objective<? super SubsetSolution, ? super DataType> objective,
                     int minSubsetSize, int maxSubsetSize, boolean orderIDs) {
    this(data, objective, minSubsetSize, maxSubsetSize, orderIDs ? Comparator.naturalOrder() : null);
}
 
Example 39
Project: jsr354-ri   File: ECBAbstractRateProvider.java View source code 6 votes vote down vote up
private RateResult findExchangeRate(ConversionQuery conversionQuery) {
	LocalDate[] dates = getQueryDates(conversionQuery);

       if (dates == null) {
       	Comparator<LocalDate> comparator = Comparator.naturalOrder();
   		LocalDate date = this.rates.keySet().stream().sorted(comparator.reversed()).findFirst().orElseThrow(() -> new MonetaryException("There is not more recent exchange rate to  rate on ECBRateProvider."));
       	return new RateResult(date, this.rates.get(date));
       } else {
       	for (LocalDate localDate : dates) {
       		Map<String, ExchangeRate> targets = this.rates.get(localDate);

       		if(Objects.nonNull(targets)) {
       			return new RateResult(localDate, targets);
       		}
		}
       	String datesOnErros = Stream.of(dates).map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.joining(","));
       	throw new MonetaryException("There is not exchange on day " + datesOnErros + " to rate to  rate on ECBRateProvider.");
       }


}
 
Example 40
Project: openjdk8-jdk   File: SortedOps.java View source code 6 votes vote down vote up
/**
 * Sort using natural order of [email protected] <T>} which must be
 * [email protected] Comparable}.
 */
OfRef(AbstractPipeline<?, T, ?> upstream) {
    super(upstream, StreamShape.REFERENCE,
          StreamOpFlag.IS_ORDERED | StreamOpFlag.IS_SORTED);
    this.isNaturalSort = true;
    // Will throw CCE when we try to sort if T is not Comparable
    this.comparator = (Comparator<? super T>) Comparator.naturalOrder();
}
 
Example 41
Project: levelup-java-examples   File: SortArray.java View source code 6 votes vote down vote up
@Test
public void sort_numeric_array_decending_in_java8 () {
	
	Integer[] uwConferenceTitles = {
			1896, 2011, 1901, 1912, 1952, 
			1959, 1962, 1999, 1897, 1906, 
			1993, 1998,  2010,  2012};

	Comparator<Integer> normal = Integer::compare;
	Comparator<Integer> reversed = normal.reversed(); 
	
	Arrays.sort(uwConferenceTitles, reversed);

	assertArrayEquals(new Integer[] {
			2012, 2011, 2010, 1999, 1998, 
			1993, 1962, 1959, 1952, 1912, 
			1906, 1901, 1897, 1896}, 
			uwConferenceTitles);
}
 
Example 42
Project: levelup-java-examples   File: SortACollection.java View source code 6 votes vote down vote up
@Test
public void sort_collection_with_java8_byweight_reverse() {

	Comparator<Wrestler> normal = ((w1, w2) -> Double.compare(
			w1.getWeightClass(), w2.getWeightClass()));

	Comparator<Wrestler> reversed = normal.reversed();

	wrestlers.sort(reversed);

	logger.info(wrestlers);

	Optional<Wrestler> wrestler = wrestlers.stream().findFirst();

	assertEquals(215, wrestler.get().getWeightClass(), 0);
}
 
Example 43
Project: openjdk8-jdk   File: BasicTest.java View source code 6 votes vote down vote up
public void testReverseComparator() {
    Comparator<String> cmpr = Comparator.reverseOrder();
    Comparator<String> cmp = cmpr.reversed();

    assertEquals(cmp.reversed(), cmpr);
    assertEquals(0, cmp.compare("a", "a"));
    assertEquals(0, cmpr.compare("a", "a"));
    assertTrue(cmp.compare("a", "b") < 0);
    assertTrue(cmpr.compare("a", "b") > 0);
    assertTrue(cmp.compare("b", "a") > 0);
    assertTrue(cmpr.compare("b", "a") < 0);
}
 
Example 44
Project: openjdk8-jdk   File: BasicTest.java View source code 6 votes vote down vote up
public void testReverseComparator2() {
    Comparator<String> cmp = (s1, s2) -> s1.length() - s2.length();
    Comparator<String> cmpr = cmp.reversed();

    assertEquals(cmpr.reversed(), cmp);
    assertEquals(0, cmp.compare("abc", "def"));
    assertEquals(0, cmpr.compare("abc", "def"));
    assertTrue(cmp.compare("abcd", "def") > 0);
    assertTrue(cmpr.compare("abcd", "def") < 0);
    assertTrue(cmp.compare("abc", "defg") < 0);
    assertTrue(cmpr.compare("abc", "defg") > 0);
}
 
Example 45
Project: judge   File: LoggerRepository.java View source code 6 votes vote down vote up
private Comparator<Logger> toComparator(Sort.Order order) {
    String property = order.getProperty();
    Comparator<Logger> c;
    if ("level".equalsIgnoreCase(property)) {
        c = BY_LEVEL;
    } else if ("name".equalsIgnoreCase(property)) {
        c = order.isIgnoreCase() ? BY_NAME_I : BY_NAME;
    } else {
        throw new IllegalArgumentException(String.format("No property %s found for type %s!", property, Logger.class.getSimpleName()));
    }
    return order.isAscending() ? c : c.reversed();
}
 
Example 46
Project: blackmarket   File: ModSelectionPane.java View source code 6 votes vote down vote up
@Override
public void accept(List<ItemType> itemTypes) {
	masterData.clear();
	List<ModMapping> modMappings = ModsMapping.getInstance().getModMappings();
	if (!itemTypes.isEmpty()) {
		List<String> itemTypesRaw = itemTypes.stream()
			.map(itemType -> itemType.itemType())
			.collect(Collectors.toList());
		modMappings = modMappings.stream()
			.filter(mm -> mm.getModType() == ModType.PSEUDO
				|| itemTypesRaw.contains(mm.getItemType()))
			.collect(Collectors.toList());
	}
	
	Comparator<ModMapping> byModType = (m1, m2) ->
    	Integer.valueOf(m1.getModType().ordinal()).compareTo(Integer.valueOf(m2.getModType().ordinal()));
    	
    	Comparator<ModMapping> byModTypeThenKey = byModType.thenComparing((m1, m2) ->
    	m1.getKey().compareTo(m2.getKey())
    );
	modMappings.sort(byModTypeThenKey);
	masterData.addAll(modMappings);
}
 
Example 47
Project: openjdk8-jdk   File: EntryComparators.java View source code 6 votes vote down vote up
private <K, V> void assertPairComparison(K k1, V v1, K k2, V v2,
                                    Comparator<Map.Entry<K, V>> ck,
                                    Comparator<Map.Entry<K, V>> cv) {
    final Map.Entry<K, V> p11 = new AbstractMap.SimpleImmutableEntry<>(k1, v1);
    final Map.Entry<K, V> p12 = new AbstractMap.SimpleImmutableEntry<>(k1, v2);
    final Map.Entry<K, V> p21 = new AbstractMap.SimpleImmutableEntry<>(k2, v1);
    final Map.Entry<K, V> p22 = new AbstractMap.SimpleImmutableEntry<>(k2, v2);

    assertTrue(ck.compare(p11, p11) == 0);
    assertTrue(ck.compare(p12, p11) == 0);
    assertTrue(ck.compare(p11, p12) == 0);
    assertTrue(ck.compare(p12, p22) < 0);
    assertTrue(ck.compare(p12, p21) < 0);
    assertTrue(ck.compare(p21, p11) > 0);
    assertTrue(ck.compare(p21, p12) > 0);

    assertTrue(cv.compare(p11, p11) == 0);
    assertTrue(cv.compare(p12, p11) > 0);
    assertTrue(cv.compare(p11, p12) < 0);
    assertTrue(cv.compare(p12, p22) == 0);
    assertTrue(cv.compare(p12, p21) > 0);
    assertTrue(cv.compare(p21, p11) == 0);
    assertTrue(cv.compare(p21, p12) < 0);

    Comparator<Map.Entry<K, V>> cmp = ck.thenComparing(cv);
    assertTrue(cmp.compare(p11, p11) == 0);
    assertTrue(cmp.compare(p12, p11) > 0);
    assertTrue(cmp.compare(p11, p12) < 0);
    assertTrue(cmp.compare(p12, p22) < 0);
    assertTrue(cmp.compare(p12, p21) < 0);
    assertTrue(cmp.compare(p21, p11) > 0);
    assertTrue(cmp.compare(p21, p12) > 0);

    cmp = cv.thenComparing(ck);
    assertTrue(cmp.compare(p11, p11) == 0);
    assertTrue(cmp.compare(p12, p11) > 0);
    assertTrue(cmp.compare(p11, p12) < 0);
    assertTrue(cmp.compare(p12, p22) < 0);
    assertTrue(cmp.compare(p12, p21) > 0);
    assertTrue(cmp.compare(p21, p11) > 0);
    assertTrue(cmp.compare(p21, p12) < 0);
}
 
Example 48
Project: openjdk8-jdk   File: EntryComparators.java View source code 6 votes vote down vote up
public void testKVComparators() {
    // Comparator<People> cmp = Comparator.naturalOrder(); // Should fail to compiler as People is not comparable
    // We can use simple comparator, but those have been tested above.
    // Thus choose to do compose for some level of interation.
    Comparator<People> cmp1 = Comparator.comparing(People::getFirstName);
    Comparator<People> cmp2 = Comparator.comparing(People::getLastName);
    Comparator<People> cmp = cmp1.thenComparing(cmp2);

    assertPairComparison(people[0], people[0], people[1], people[1],
                     Map.Entry.<People, People>comparingByKey(cmp),
                     Map.Entry.<People, People>comparingByValue(cmp));

}
 
Example 49
Project: LambdaDojo   File: S206LambdaForCompositeFunction.java View source code 6 votes vote down vote up
private void sortPersonAnswer2() {
    List<Person> persons = Arrays.asList(
            new Person("James", "Brown"),
            new Person("David", "Crosby"),
            new Person("James", "Taylor"),
            new Person("Jackson", "Brown"),
            new Person("Neil", "Young"),
            new Person("Coco", "Taylor")
    );

    // ????????????
    Comparator<Person> comparatorLast = (p1, p2) -> {
        String last1 = p1.getLast();
        String last2 = p2.getLast();
        return last1.compareTo(last2);
    };

    // ????????????
    Comparator<Person> comparatorFirst = (p1, p2) -> {
            String first1 = p1.getFirst();
            String first2 = p2.getFirst();
            return first1.compareTo(first2);
    };

    // ?????????????????????????????????
    Comparator<Person> comparator = comparatorLast.thenComparing(comparatorFirst);

    Collections.sort(persons, comparator);
    System.out.println(persons);
}
 
Example 50
Project: LambdaDojo   File: S206LambdaForCompositeFunction.java View source code 6 votes vote down vote up
private void sortPersonAnswer2() {
    List<Person> persons = Arrays.asList(
            new Person("James", "Brown"),
            new Person("David", "Crosby"),
            new Person("James", "Taylor"),
            new Person("Jackson", "Brown"),
            new Person("Neil", "Young"),
            new Person("Coco", "Taylor")
    );

    // ????????????
    Comparator<Person> comparatorLast = (p1, p2) -> {
        String last1 = p1.getLast();
        String last2 = p2.getLast();
        return last1.compareTo(last2);
    };

    // ????????????
    Comparator<Person> comparatorFirst = (p1, p2) -> {
            String first1 = p1.getFirst();
            String first2 = p2.getFirst();
            return first1.compareTo(first2);
    };

    // ?????????????????????????????????
    Comparator<Person> comparator = comparatorLast.thenComparing(comparatorFirst);

    Collections.sort(persons, comparator);
    System.out.println(persons);
}
 
Example 51
Project: goworks   File: BaseCompletionController.java View source code 5 votes vote down vote up
@Override
public Selection getSelection(List<? extends CompletionItem> items, List<? extends CompletionItem> declarationItems) {
    Comparator<CompletionItem> comparator = getComparator(CompletionResultSet.TEXT_SORT_TYPE);

    String completionPrefix = getCompletionPrefix();
    String evaluatedText = completionPrefix;
    while (true) {
        CompletionItem bestMatch = null;
        int bestMatchValue = 0;
        int prefixMatch = 0;
        CompletionMatchEvaluator evaluator = getCompletionMatchEvaluator(evaluatedText);
        for (CompletionItem item : items) {
            int matchValue = evaluator.getMatchStrength(item);
            if (matchValue > 0) {
                if ((matchValue & (CompletionMatchEvaluator.PREFIX_CASE_SENSITIVE | CompletionMatchEvaluator.PREFIX)) != 0) {
                    prefixMatch++;
                }

                boolean improved = matchValue > bestMatchValue
                    || (matchValue == bestMatchValue && comparator.compare(item, bestMatch) < 0);

                if (improved) {
                    bestMatch = item;
                    bestMatchValue = matchValue;
                }
            }
        }

        if (bestMatch != null) {
            int index = items.indexOf(bestMatch);
            boolean selected =
                declarationItems.isEmpty()
                && (!(bestMatch instanceof AbstractCompletionItem) || ((AbstractCompletionItem)bestMatch).allowInitialSelection())
                && evaluatedText != null && !evaluatedText.isEmpty();

            boolean unique = !completionPrefix.isEmpty()
                && (prefixMatch == 1)
                && evaluatedText.length() == completionPrefix.length();

            return new Selection(index, selected, unique);
        }

        if (evaluatedText.length() == 0) {
            break;
        }

        evaluatedText = evaluatedText.substring(0, evaluatedText.length() - 1);
    }

    return Selection.DEFAULT;
}
 
Example 52
Project: Technomap   File: FilterIteratorFactory.java View source code 5 votes vote down vote up
protected static IntIterator getRangeIterator(Table t, RangePredicate rp) {
    ColumnExpression col;
    Expression l, r;
    
    // make sure columns are of the right type
    if ( !(rp.getMiddleExpression() instanceof ColumnExpression) ||
            ExpressionAnalyzer.hasDependency(rp.getLeftExpression()) ||
            ExpressionAnalyzer.hasDependency(rp.getRightExpression()) )
    {
        return null;
    }
    
    // assign variables
    col = (ColumnExpression)rp.getMiddleExpression();
    l = rp.getLeftExpression();
    r = rp.getRightExpression();
    
    // if table has index of the right type, use it
    Comparator cmp = rp.getComparator();
    Index index = t.getIndex(col.getColumnName());
    
    if ( index == null || !cmp.equals(index.getComparator()) )
        return null;
    
    int operation = rp.getOperation();
    Class ltype = t.getColumnType(col.getColumnName());
    
    // TODO safety check literal types
    
    // get the index type
    int indexType;
    switch ( operation ) {
    case RangePredicate.IN_IN:
        indexType = Index.TYPE_AII;
        break;
    case RangePredicate.IN_EX:
        indexType = Index.TYPE_AIE;
        break;
    case RangePredicate.EX_IN:
        indexType = Index.TYPE_AEI;
        break;
    case RangePredicate.EX_EX:
        indexType = Index.TYPE_AEE;
        break;
    default:
        throw new IllegalStateException(); // should never occur
    }
    
    // get the indexed rows
    if ( ltype == int.class ) {
        return index.rows(l.getInt(null), r.getInt(null), indexType);
    } else if ( ltype == long.class ) {
        return index.rows(l.getLong(null), r.getLong(null), indexType);
    } else if ( ltype == float.class ) {
        return index.rows(l.getFloat(null), r.getFloat(null), indexType);
    } else if ( ltype == double.class ) {
        return index.rows(l.getDouble(null), r.getDouble(null), indexType);
    } else {
        return index.rows(l.get(null), r.get(null), indexType);
    }
}
 
Example 53
Project: Prefuse   File: FilterIteratorFactory.java View source code 5 votes vote down vote up
protected static IntIterator getRangeIterator(Table t, RangePredicate rp) {
    ColumnExpression col;
    Expression l, r;
    
    // make sure columns are of the right type
    if ( !(rp.getMiddleExpression() instanceof ColumnExpression) ||
            ExpressionAnalyzer.hasDependency(rp.getLeftExpression()) ||
            ExpressionAnalyzer.hasDependency(rp.getRightExpression()) )
    {
        return null;
    }
    
    // assign variables
    col = (ColumnExpression)rp.getMiddleExpression();
    l = rp.getLeftExpression();
    r = rp.getRightExpression();
    
    // if table has index of the right type, use it
    Comparator cmp = rp.getComparator();
    Index index = t.getIndex(col.getColumnName());
    
    if ( index == null || !cmp.equals(index.getComparator()) )
        return null;
    
    int operation = rp.getOperation();
    Class ltype = t.getColumnType(col.getColumnName());
    
    // TODO safety check literal types
    
    // get the index type
    int indexType;
    switch ( operation ) {
    case RangePredicate.IN_IN:
        indexType = Index.TYPE_AII;
        break;
    case RangePredicate.IN_EX:
        indexType = Index.TYPE_AIE;
        break;
    case RangePredicate.EX_IN:
        indexType = Index.TYPE_AEI;
        break;
    case RangePredicate.EX_EX:
        indexType = Index.TYPE_AEE;
        break;
    default:
        throw new IllegalStateException(); // should never occur
    }
    
    // get the indexed rows
    if ( ltype == int.class ) {
        return index.rows(l.getInt(null), r.getInt(null), indexType);
    } else if ( ltype == long.class ) {
        return index.rows(l.getLong(null), r.getLong(null), indexType);
    } else if ( ltype == float.class ) {
        return index.rows(l.getFloat(null), r.getFloat(null), indexType);
    } else if ( ltype == double.class ) {
        return index.rows(l.getDouble(null), r.getDouble(null), indexType);
    } else {
        return index.rows(l.get(null), r.get(null), indexType);
    }
}