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 generate more good examples.
Example 1
Project: couchmove   File: FileUtils.java   View source code 8 votes vote down vote up
/**
 * If the file is a Directory, calculate the checksum of all files in this directory (one level)
 * Else, calculate the checksum of the file matching extensions
 *
 * @param filePath   file or folder
 * @param extensions of files to calculate checksum of
 * @return checksum
 */
public static String calculateChecksum(@NotNull Path filePath, String... extensions) {
    if (filePath == null || !Files.exists(filePath)) {
        throw new CouchmoveException("File is null or doesn't exists");
    }
    if (Files.isDirectory(filePath)) {
        return directoryStream(filePath, extensions)
                .sorted(Comparator.comparing(path -> path.getFileName().toString()))
                .map(FileUtils::calculateChecksum)
                .reduce(String::concat)
                .map(DigestUtils::sha256Hex)
                .orElse(null);
    }
    try {
        return DigestUtils.sha256Hex(toByteArray(filePath.toUri()));
    } catch (IOException e) {
        throw new CouchmoveException("Unable to calculate file checksum '" + filePath.getFileName().toString() + "'");
    }
}
 
Example 2
Project: guava-mock   File: ImmutableSortedSet.java   View source code 6 votes vote down vote up
/**
 * Returns an immutable sorted set containing the given elements sorted by
 * the given {@code Comparator}. When multiple elements are equivalent
 * according to {@code compare()}, only the first one specified is
 * included. This method iterates over {@code elements} at most once.
 *
 * <p>Despite the method name, this method attempts to avoid actually copying
 * the data when it is safe to do so. The exact circumstances under which a
 * copy will or will not be performed are undocumented and subject to change.
 *
 * @throws NullPointerException if {@code comparator} or any of {@code
 *         elements} is null
 */
public static <E> ImmutableSortedSet<E> copyOf(
    Comparator<? super E> comparator, Iterable<? extends E> elements) {
  checkNotNull(comparator);
  boolean hasSameComparator = SortedIterables.hasSameComparator(comparator, elements);

  if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
    @SuppressWarnings("unchecked")
    ImmutableSortedSet<E> original = (ImmutableSortedSet<E>) elements;
    if (!original.isPartialView()) {
      return original;
    }
  }
  @SuppressWarnings("unchecked") // elements only contains E's; it's safe.
  E[] array = (E[]) Iterables.toArray(elements);
  return construct(comparator, array.length, array);
}
 
Example 3
Project: jetfuel   File: SortNode.java   View source code 6 votes vote down vote up
public final Comparator<Object[]> createObjectArrayComparator() {
	return new Comparator<Object[]>() {
		final int ordinal = column.getColumnIndex();

		@SuppressWarnings({ "rawtypes", "unchecked" })
		public int compare(Object[] left, Object[] right) {
			int ascSort = 0;
			Object a = left[ordinal];
			Object b = right[ordinal];
			if (a == null)
				ascSort = (b == null)
						? 0
						: 1;
			else if (b == null)
				ascSort = -1;
			else
				ascSort = ((Comparable) a).compareTo(b);
			return direction == SortDirection.ASC
					? ascSort
					: -ascSort;
		}
	};
}
 
Example 4
Project: googles-monorepo-demo   File: UnsignedBytesTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testLexicographicalComparatorLongInputs() {
  for (Comparator<byte[]> comparator : Arrays.asList(
      UnsignedBytes.lexicographicalComparator(),
      UnsignedBytes.lexicographicalComparatorJavaImpl())) {
    for (int i = 0; i < 32; i++) {
      byte[] left = new byte[32];
      byte[] right = new byte[32];

      assertTrue(comparator.compare(left, right) == 0);
      left[i] = 1;
      assertTrue(comparator.compare(left, right) > 0);
      assertTrue(comparator.compare(right, left) < 0);
    }
  }
}
 
Example 5
Project: googles-monorepo-demo   File: TreeMultisetTest.java   View source code 6 votes vote down vote up
public void testCustomComparator() throws Exception {
  Comparator<String> comparator = new Comparator<String>() {
    @Override
    public int compare(String o1, String o2) {
      return o2.compareTo(o1);
    }
  };
  TreeMultiset<String> ms = TreeMultiset.create(comparator);

  ms.add("b");
  ms.add("c");
  ms.add("a");
  ms.add("b");
  ms.add("d");

  assertThat(ms).containsExactly("d", "c", "b", "b", "a").inOrder();

  SortedSet<String> elementSet = ms.elementSet();
  assertEquals("d", elementSet.first());
  assertEquals("a", elementSet.last());
  assertEquals(comparator, elementSet.comparator());
}
 
Example 6
Project: CustomWorldGen   File: PersistentRegistryManager.java   View source code 6 votes vote down vote up
public static void fireRegistryEvents()
{
    List<ResourceLocation> registryKeys = Lists.newArrayList(PersistentRegistry.ACTIVE.registries.keySet());
    Collections.sort(registryKeys, new Comparator<ResourceLocation>()
    {
        @Override
        public int compare(ResourceLocation o1, ResourceLocation o2)
        {
            return o1.toString().compareToIgnoreCase(o2.toString());
        }
    });
    fireRegistryEvent(PersistentRegistry.ACTIVE.registries, BLOCKS);
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject any blocks
    fireRegistryEvent(PersistentRegistry.ACTIVE.registries, ITEMS);
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject any items
    for (ResourceLocation rl : registryKeys) {
        if (rl == BLOCKS || rl == ITEMS) continue;
        fireRegistryEvent(PersistentRegistry.ACTIVE.registries, rl);
    }
    ObjectHolderRegistry.INSTANCE.applyObjectHolders(); // inject everything else
}
 
Example 7
Project: r8   File: MinifiedNameMapPrinter.java   View source code 6 votes vote down vote up
private void write(DexProgramClass clazz, PrintStream out) {
  seenTypes.add(clazz.type);
  DexString descriptor = namingLens.lookupDescriptor(clazz.type);
  out.print(DescriptorUtils.descriptorToJavaType(clazz.type.descriptor.toSourceString()));
  out.print(" -> ");
  out.print(DescriptorUtils.descriptorToJavaType(descriptor.toSourceString()));
  out.println(":");
  write(sortedCopy(
      clazz.instanceFields(), Comparator.comparing(DexEncodedField::toSourceString)), out);
  write(sortedCopy(
      clazz.staticFields(), Comparator.comparing(DexEncodedField::toSourceString)), out);
  write(sortedCopy(
      clazz.directMethods(), Comparator.comparing(DexEncodedMethod::toSourceString)), out);
  write(sortedCopy(
      clazz.virtualMethods(), Comparator.comparing(DexEncodedMethod::toSourceString)), out);
}
 
Example 8
Project: azure-libraries-for-java   File: CosmosDBAccountImpl.java   View source code 6 votes vote down vote up
private void ensureFailoverIsInitialized() {
    if (this.isInCreateMode()) {
        return;
    }

    if (!this.hasFailoverPolicyChanges) {
        this.failoverPolicies.clear();
        FailoverPolicyInner[] policyInners = new FailoverPolicyInner[this.inner().failoverPolicies().size()];
        this.inner().failoverPolicies().toArray(policyInners);
        Arrays.sort(policyInners, new Comparator<FailoverPolicyInner>() {
            @Override
            public int compare(FailoverPolicyInner o1, FailoverPolicyInner o2) {
                return o1.failoverPriority().compareTo(o2.failoverPriority());
            }
        });

        for (int i = 0; i < policyInners.length; i++) {
            this.failoverPolicies.add(policyInners[i]);
        }

        this.hasFailoverPolicyChanges = true;
    }
}
 
Example 9
Project: openjdk-jdk10   File: DefaultMXBeanMappingFactory.java   View source code 6 votes vote down vote up
@Override
final Object toNonNullOpenValue(Object value)
        throws OpenDataException {
    final Collection<?> valueCollection = (Collection<?>) value;
    if (valueCollection instanceof SortedSet<?>) {
        Comparator<?> comparator =
            ((SortedSet<?>) valueCollection).comparator();
        if (comparator != null) {
            final String msg =
                "Cannot convert SortedSet with non-null comparator: " +
                comparator;
            throw openDataException(msg, new IllegalArgumentException(msg));
        }
    }
    final Object[] openArray = (Object[])
        Array.newInstance(getOpenClass().getComponentType(),
                          valueCollection.size());
    int i = 0;
    for (Object o : valueCollection)
        openArray[i++] = elementMapping.toOpenValue(o);
    return openArray;
}
 
Example 10
Project: googles-monorepo-demo   File: ImmutableSortedSet.java   View source code 6 votes vote down vote up
private static <E> ImmutableSortedSet<E> copyOfInternal(
    Comparator<? super E> comparator, Iterable<? extends E> elements,
    boolean fromSortedSet) {
  checkNotNull(comparator);

  boolean hasSameComparator
      = fromSortedSet || hasSameComparator(elements, comparator);
  if (hasSameComparator && (elements instanceof ImmutableSortedSet)) {
    @SuppressWarnings("unchecked")
    ImmutableSortedSet<E> result = (ImmutableSortedSet<E>) elements;
    boolean isSubset = (result instanceof RegularImmutableSortedSet)
        && ((RegularImmutableSortedSet) result).isSubset;
    if (!isSubset) {
      // Only return the original copy if this immutable sorted set isn't
      // a subset of another, to avoid memory leak.
      return result;
    }
  }
  return copyOfInternal(comparator, elements.iterator());
}
 
Example 11
Project: Catter2   File: FavoritesActivity.java   View source code 6 votes vote down vote up
private void updateFavorites(SharedPreferences pref) {
    String prefKey = String.format(SP_USER_FAVORITES_KEY, userToken);
    Log.d(TAG, "PrefKey: " + prefKey);
    Set<String> entriesSet = pref.getStringSet(prefKey, new HashSet<String>());

    ArrayList<FavoriteModel> favorites = new ArrayList<>(entriesSet.size());
    for (String entry : entriesSet) {
        String[] decoded = entry.split(";");
        favorites.add(new FavoriteModel(Long.valueOf(decoded[1]), decoded[0]));
    }

    Collections.sort(favorites, new Comparator<FavoriteModel>() {
        @Override
        public int compare(FavoriteModel o1, FavoriteModel o2) {
            return (int) (o2.getTimeAdded() - o1.getTimeAdded());
        }
    });

    ArrayList<String> urlsSorted = new ArrayList<>(favorites.size());
    for (FavoriteModel favorite : favorites) {
        urlsSorted.add(favorite.getUrl());
    }

    Log.d(TAG, "Updated favorites: " + urlsSorted.toString());
    rvAdapter.updateImageUrls(new ArrayList<>(urlsSorted));
}
 
Example 12
Project: mycat-src-1.6.1-RELEASE   File: TimSort.java   View source code 6 votes vote down vote up
/**
 * Creates a TimSort instance to maintain the state of an ongoing sort.
 *
 * @param a the array to be sorted
 * @param c the comparator to determine the order of the sort
 */
private SortState(Buffer a, Comparator<? super K> c, int len) {
  this.aLength = len;
  this.a = a;
  this.c = c;

  // Allocate temp storage (which may be increased later if necessary)
  tmpLength = len < 2 * INITIAL_TMP_STORAGE_LENGTH ? len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
  tmp = s.allocate(tmpLength);

  /*
   * Allocate runs-to-be-merged stack (which cannot be expanded).  The
   * stack length requirements are described in listsort.txt.  The C
   * version always uses the same stack length (85), but this was
   * measured to be too expensive when sorting "mid-sized" arrays (e.g.,
   * 100 elements) in Java.  Therefore, we use smaller (but sufficiently
   * large) stack lengths for smaller arrays.  The "magic numbers" in the
   * computation below must be changed if MIN_MERGE is decreased.  See
   * the MIN_MERGE declaration above for more information.
   */
  int stackLen = (len <    120  ?  5 :
                  len <   1542  ? 10 :
                  len < 119151  ? 19 : 40);
  runBase = new int[stackLen];
  runLen = new int[stackLen];
}
 
Example 13
Project: FreeCol   File: Colony.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Unit getDefendingUnit(Unit attacker) {
    if (displayUnitCount > 0) {
        // There are units, but we don't see them
        return null;
    }

    // Note that this function will only return a unit working
    // inside the colony.  Typically, colonies are also defended
    // by units outside the colony on the same tile.  To consider
    // units outside the colony as well, use
    // @see Tile#getDefendingUnit instead.
    final CombatModel cm = getGame().getCombatModel();
    final Comparator<Unit> comp
            = cachingDoubleComparator(u -> cm.getDefencePower(attacker, u));
    return maximize(getUnits(), comp);
}
 
Example 14
Project: MoodSwings   File: MoodList.java   View source code 6 votes vote down vote up
/**
 *
 * @return
 *
 * Get the most recent mood from the end of the sorted array.
 */
public MoodEvent getMostRecent() {
    Collections.sort(moodEvents, new Comparator<MoodEvent>() {
        public int compare(MoodEvent mood1, MoodEvent mood2) {
            long t1 = 0;
            long t2 = 0;
            try {
                t1 = COMBINED_DATE_FORMAT.parse(
                        String.format("%1$s %2$s", mood1.getDate(), mood1.getTime()))
                        .getTime();
                t2 = COMBINED_DATE_FORMAT.parse(
                        String.format("%1$s %2$s", mood2.getDate(), mood2.getTime()))
                        .getTime();
            } catch (ParseException e) {
                return 1;
            }
            return Long.valueOf(t2).compareTo(t1);
        }
    });
    return getMoodEvent(0);//(moodEvents.size() - 1);
}
 
Example 15
Project: s-store   File: Range.java   View source code 6 votes vote down vote up
/**
 * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in
 * this range.
 */
public boolean containsAll(Iterable<? extends C> values) {
  if (Iterables.isEmpty(values)) {
    return true;
  }

  // this optimizes testing equality of two range-backed sets
  if (values instanceof SortedSet) {
    SortedSet<? extends C> set = cast(values);
    Comparator<?> comparator = set.comparator();
    if (Ordering.natural().equals(comparator) || comparator == null) {
      return contains(set.first()) && contains(set.last());
    }
  }

  for (C value : values) {
    if (!contains(value)) {
      return false;
    }
  }
  return true;
}
 
Example 16
Project: FreeCol   File: DebugUtils.java   View source code 6 votes vote down vote up
/**
 * Debug action to change the roles of a unit.
 *
 * Called from tile popup menu.
 *
 * @param freeColClient The {@code FreeColClient} for the game.
 * @param unit The {@code Unit} to change the role of.
 */
public static void changeRole(final FreeColClient freeColClient,
                              final Unit unit) {
    final FreeColServer server = freeColClient.getFreeColServer();
    final Game sGame = server.getGame();
    final Unit sUnit = sGame.getFreeColGameObject(unit.getId(), Unit.class);
    final GUI gui = freeColClient.getGUI();
    final Function<Role, ChoiceItem<Role>> roleMapper = r ->
        new ChoiceItem<Role>(r.getId(), r);

    Role roleChoice = gui.getChoice(null,
        StringTemplate.template("prompt.selectRole"), "cancel",
        transform(sGame.getSpecification().getRoles(), alwaysTrue(),
                  roleMapper, Comparator.naturalOrder()));
    if (roleChoice == null) return;

    sUnit.changeRole(roleChoice, roleChoice.getMaximumCount());
    reconnect(freeColClient);
}
 
Example 17
Project: PrivacyStreams   File: ByFieldStreamSorter.java   View source code 5 votes vote down vote up
@Override
protected void reorder(List<Item> items) {
    Collections.sort(items, new Comparator<Item>() {
        @Override
        public int compare(Item item1, Item item2) {
            Comparable value1 = item1.getValueByField(fieldToSort);
            Comparable value2 = item2.getValueByField(fieldToSort);
            return value1.compareTo(value2);
        }
    });
}
 
Example 18
Project: lib-commons-httpclient   File: TestCookiePathComparator.java   View source code 5 votes vote down vote up
public void testEquality2() {
    Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a/", null, false); 
    Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false);
    Comparator comparator = new CookiePathComparator();
    assertTrue(comparator.compare(cookie1, cookie2) == 0);
    assertTrue(comparator.compare(cookie2, cookie1) == 0);
}
 
Example 19
Project: alevin-svn2   File: FullKnowledgeClusterHead.java   View source code 5 votes vote down vote up
@Override
public Collection<ClusterHead> findClusterCandidates(final VirtualNetwork vNetwork, ClusterHead orig) {

	LinkedList<FullKnowledgeClusterHead> result = new LinkedList<FullKnowledgeClusterHead>();
	LinkedList<LockTree> queue = new LinkedList<LockTree>();
	
	if (!subLockTree.isFullyLocked()) {
		queue.add(subLockTree);
	}

	while (!queue.isEmpty()) {
		LockTree current = queue.pop();
		if (current.getChildren() != null) {
			for (LockTree t : current.getChildren()) {
				//TODO: Here we got Information of Children without sending a message!
				if (estimationAlgorithm.estimate(
						((FullKnowledgeClusterHead) t.getClusterHead()).getCluster(), vNetwork) >= 1.0d) {
					if (t.isUnLocked()) {
						queue.addLast(t);
					}
				}
			}
		}
		if (current.getClusterHead() != orig) {
			result.add((FullKnowledgeClusterHead) current.getClusterHead());
		}
	}

	Collections.sort(result, new Comparator<FullKnowledgeClusterHead>() {
		@Override
		public int compare(FullKnowledgeClusterHead o1, FullKnowledgeClusterHead o2) {
			
			double i1 = estimationAlgorithm.estimate(o1.getCluster(), vNetwork);
			double i2 = estimationAlgorithm.estimate(o2.getCluster(), vNetwork);
			
			if (i1 < i2) {
				return -1;
			}
			if (i1 > i2) {
				return 1;
			}
			
			return 0;
		}
	});

	return new LinkedList<ClusterHead>(result);
}
 
Example 20
Project: incubator-netbeans   File: TableSorter.java   View source code 5 votes vote down vote up
/**
 * Sets comparator that will be used to compare values in the specified column. Note that the Comparator will obtain
 * row indices (as Integer objects) to compare and NOT actual cell values.
 * 
 * @param column model index of the column to be sorted 
 * @param comparator comparator that will sort the given column
 */ 
public void setColumnComparator(int column, Comparator comparator) {
    if (comparator == null) {
        columnComparators.remove(Integer.valueOf(column));
    } else {
        columnComparators.put(Integer.valueOf(column), comparator);
    }
}
 
Example 21
Project: cyberduck   File: AttributedList.java   View source code 5 votes vote down vote up
/**
 * The CopyOnWriteArrayList iterator does not support remove but the sort implementation
 * makes use of it. Provide our own implementation here to circumvent.
 *
 * @param comparator The comparator to use
 * @see java.util.Collections#sort(java.util.List, java.util.Comparator)
 * @see java.util.concurrent.CopyOnWriteArrayList#iterator()
 */
private void doSort(final Comparator<E> comparator) {
    if(null == comparator) {
        return;
    }
    if(log.isDebugEnabled()) {
        log.debug(String.format("Sort list %s with comparator %s", this, comparator));
    }
    Collections.sort(impl, comparator);
}
 
Example 22
Project: parabuild-ci   File: SortedMap.java   View source code 5 votes vote down vote up
public SortedMap(SessionImplementor session, CollectionPersister persister, Comparator comparator, Serializable disassembled, Object owner)
throws HibernateException {
	super(session);
	this.comparator=comparator;
	beforeInitialize(persister);
	Serializable[] array = (Serializable[]) disassembled;
	for (int i=0; i<array.length; i+=2 ) map.put(
		persister.getIndexType().assemble( array[i], session, owner ),
		persister.getElementType().assemble( array[i+1], session, owner )
	);
	setInitialized();
}
 
Example 23
Project: BrainControl   File: StrategyStorage.java   View source code 5 votes vote down vote up
/**
 * Sorts a given list of strategies based on their successRate
 * 
 * @param strategyList the list of strategies to be sorted
 * @return the sorted list of strategies
 */
private ArrayList<Strategy> sortStrategies(ArrayList<Strategy> strategyList){
	Collections.sort(strategyList, new Comparator<Strategy>() 
	{
	    @Override
	    public int compare(Strategy s, Strategy t) 
	    {
	        return (int)(s.getSuccessRate() - t.getSuccessRate());
	    }
	});	
	return strategyList;
}
 
Example 24
Project: AquamarineLake   File: Lambda.java   View source code 5 votes vote down vote up
public static void main(String[] args)
{
	int a = 4;
	int b = 3;
	
	Comparator<Integer> xd = (x, y) -> {
		if (x > y) return -1;
		if (x == y) return 0;
		if (x < y) return 1;
		return -2;
	};
	
	System.out.println(xd.compare(a, b));
	
}
 
Example 25
Project: featurea   File: TimSort.java   View source code 5 votes vote down vote up
@SuppressWarnings("fallthrough")
private static <T> void binarySort(T[] a, int lo, int hi, int start, Comparator<? super T> c) {
    if (DEBUG) assert lo <= start && start <= hi;
    if (start == lo) start++;
    for (; start < hi; start++) {
        T pivot = a[start];
        int left = lo;
        int right = start;
        if (DEBUG) assert left <= right;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (c.compare(pivot, a[mid]) < 0) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        if (DEBUG) assert left == right;
        int n = start - left;
        switch (n) {
            case 2:
                a[left + 2] = a[left + 1];
            case 1:
                a[left + 1] = a[left];
                break;
            default:
                System.arraycopy(a, left, a, left + 1, n);
        }
        a[left] = pivot;
    }
}
 
Example 26
Project: alfresco-repository   File: VersionHistoryImpl.java   View source code 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "deprecation" })
private void readObject(ObjectInputStream is) throws ClassNotFoundException, IOException
{
    GetField fields = is.readFields();
    if (fields.defaulted("versionsByLabel"))
    {
        // This is a V2.2 class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (HashMap<String, Version>) fields.get("versions", new HashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        // Need this comparator as versionsByLabel is not a LinkedHashMap in this version 
        this.versionComparatorDesc = new VersionLabelComparator(); 
    }
    else if (fields.defaulted("versionComparatorDesc"))
    {
        // This is a V3.1.0 class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (HashMap<String, Version>) fields.get("versionsByLabel", new HashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        // Need this comparator as versionsByLabel is not a LinkedHashMap in this version 
        this.versionComparatorDesc = new VersionLabelComparator(); 
    }
    else
    {
        // This is a V4.1.3 (and 4.0.2 HF) class
        // The old 'rootVersion' maps to the current 'rootVersion'
        this.versionsByLabel = (Map<String, Version>) fields.get("versionsByLabel", new LinkedHashMap<String, Version>());
        // The old 'versionHistory' maps to the current 'versionHistory'
        this.versionHistory = (HashMap<String, String>) fields.get("versionHistory", new HashMap<String, String>());
        this.versionComparatorDesc = (Comparator<Version>) fields.get("versionComparatorDesc", null); 
    }
}
 
Example 27
Project: android-retrostreams   File: Spliterators.java   View source code 5 votes vote down vote up
private static <T> Spliterator<T> setSpliterator(Set<? extends T> c, String name) {
    if (!IS_HARMONY_ANDROID && NATIVE_SPECIALIZATION) {
        if ("java.util.HashMap$EntrySet".equals(name)) {
            return (Spliterator<T>) HMSpliterators
                    .<Object, Object> getEntrySetSpliterator((Set<Map.Entry<Object, Object>>) c);
        }
        if ("java.util.HashMap$KeySet".equals(name)) {
            return HMSpliterators.getKeySetSpliterator((Set<T>) c);
        }
    }

    if (c instanceof LinkedHashSet) {
        return spliterator(c, Spliterator.DISTINCT | Spliterator.ORDERED);
    }

    if (!IS_HARMONY_ANDROID && NATIVE_SPECIALIZATION) {
        if (c instanceof HashSet) {
            return HMSpliterators.getHashSetSpliterator((HashSet<T>) c);
        }
    }

    // default from j.u.SortedSet
    if (c instanceof SortedSet) {
        return new IteratorSpliterator<T>(c, Spliterator.DISTINCT
                | Spliterator.SORTED | Spliterator.ORDERED) {
            @Override
            public Comparator<? super T> getComparator() {
                return ((SortedSet<T>) c).comparator();
            }
        };
    }

    if ((NATIVE_SPECIALIZATION || IS_ANDROID) && c instanceof CopyOnWriteArraySet) {
        return COWArraySetSpliterator
                .spliterator((CopyOnWriteArraySet<T>) c);
    }

    // default from j.u.Set
    return Spliterators.spliterator(c, Spliterator.DISTINCT);
}
 
Example 28
Project: FlashLib   File: CvProcessing.java   View source code 5 votes vote down vote up
/**
 * Sorts the contours by their size and removes contours for the bottom of the list if the list contains
 * too many contours. 
 * 
 * @param contours list of contours
 * @param amount the maximum amount of contours that should remain after the operation
 * @see #filterByComparator(List, int, Comparator)
 */
public static void filterForSmallestContours(List<MatOfPoint> contours, int amount){
	Comparator<MatOfPoint> sizeComparer = (MatOfPoint o1, MatOfPoint o2) ->{
		if(o1.total() > o2.total()) return 1;
		else if(o2.total() > o1.total()) return -1;
		return 0;
	};
	filterByComparator(contours, amount, sizeComparer);
}
 
Example 29
Project: Cognizant-Intelligent-Test-Scripter   File: ORUtils.java   View source code 5 votes vote down vote up
public static void sort(ORRootInf root) {
    Collections.sort(root.getPages(), new Comparator<ORPageInf>() {
        @Override
        public int compare(ORPageInf t, ORPageInf t1) {
            return t.getName().compareToIgnoreCase(t1.getName());
        }
    });
}
 
Example 30
Project: s-store   File: HistogramUtil.java   View source code 5 votes vote down vote up
/**
 * Returns the list of values sorted in descending order by cardinality
 * @param h
 * @return
 */
public static <X> Collection<X> sortedValues(final Histogram<X> h) {
    SortedSet<X> sorted = new TreeSet<X>(new Comparator<X>() {
        public int compare(final X item0, final X item1) {
            final Long v0 = h.get(item0);
            final Long v1 = h.get(item1);
            if (v0.equals(v1))
                return (-1);
            return (v1.compareTo(v0));
          }
    });
    sorted.addAll(h.values());
    return (sorted);
}
 
Example 31
Project: guava-mock   File: SetsTest.java   View source code 5 votes vote down vote up
/**
 * Utility method to verify that the given SortedSet is equal to and
 * hashes identically to a set constructed with the elements in the
 * given iterable.  Also verifies that the comparator is the same as the
 * given comparator.
 */
private static <E> void verifySortedSetContents(
    SortedSet<E> set, Iterable<E> iterable,
    @Nullable Comparator<E> comparator) {
  assertSame(comparator, set.comparator());
  verifySetContents(set, iterable);
}
 
Example 32
Project: CustomWorldGen   File: GameRegistry.java   View source code 5 votes vote down vote up
private static void computeSortedGeneratorList()
{
    ArrayList<IWorldGenerator> list = Lists.newArrayList(worldGenerators);
    Collections.sort(list, new Comparator<IWorldGenerator>()
    {
        @Override
        public int compare(IWorldGenerator o1, IWorldGenerator o2)
        {
            return Ints.compare(worldGeneratorIndex.get(o1), worldGeneratorIndex.get(o2));
        }
    });
    sortedGeneratorList = ImmutableList.copyOf(list);
}
 
Example 33
Project: Apriori   File: TieBreakerTest.java   View source code 5 votes vote down vote up
/**
 * Tests the functionality of a multiple tie-breaking strategies for item sets.
 */
@Test
public final void testMultipleTieBreakingStrategiesForItemSets() {
    ItemSet itemSet1 = mock(ItemSet.class);
    ItemSet itemSet2 = mock(ItemSet.class);
    Comparator<ItemSet> comparator1 = (o1, o2) -> 0;
    Comparator<ItemSet> comparator2 = (o1, o2) -> -1;
    TieBreaker<ItemSet> tieBreaker = TieBreaker.forItemSets().custom(comparator1)
            .custom(comparator2);
    assertEquals(-1, tieBreaker.compare(itemSet1, itemSet2));
}
 
Example 34
Project: android-agenda-view   File: AgendaView.java   View source code 5 votes vote down vote up
protected void drawShifts(Canvas canvas) {
    int px = 10;

    Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextPaint.setTextSize(DEPARTMENT_FONT_SIZE);
    mTextPaint.setColor(Color.DKGRAY);

    Paint mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mLinePaint.setColor(Color.LTGRAY);

    ArrayList<List<IShift>> departments = new ArrayList<>();
    departments.addAll(ShiftHashData.values());

    Collections.sort(departments, new Comparator<List<IShift>>() {
        @Override
        public int compare(List<IShift> lhs, List<IShift> rhs) {
            return lhs.get(0).getSectionName().compareTo(rhs.get(0).getSectionName());
        }
    });

    for (List<IShift> department : departments) {
        List<ShiftLevel> added = new ArrayList<>();
        MaxHeight = 0;


        for (IShift shift : department) {
            // To check if the shift collides with other in the department
            drawRoundRect(canvas, shift, department, added);
        }

        IShift firstElement = department.get(0);

        // Write Dep. Name
        canvas.drawText(firstElement.getSectionName(), px, py + DEPARTMENT_FONT_SIZE + DEPARTMENT_VERTICAL_PADDING, mTextPaint);
        py = ROUND_RECT_PADDING + MaxHeight;
        canvas.drawLine(0, py, viewWidth, py, mLinePaint);
    }
}
 
Example 35
Project: hue   File: JoinDetector.java   View source code 5 votes vote down vote up
private List<Entry<String, Integer>> sortMapByRatios(){
	Comparator<Entry<String, Integer>> byValue = (entry1, entry2) -> entry1.getValue().compareTo(
            entry2.getValue());

    List<Entry<String, Integer>> l = ratioMap
            .entrySet()
            .stream()
            .sorted(byValue.reversed())
            .collect(Collectors.toList());
    logger.debug("Sorted ratioMap: /n" + l);

    return l;
}
 
Example 36
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   View source code 5 votes vote down vote up
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 37
Project: ProjectAres   File: Comparators.java   View source code 5 votes vote down vote up
public static <T, U> Comparator<T> instancesFirst(Class<U> type, Comparator<U> c) {
    return (a, b) -> {
        if(type.isInstance(a)) {
            if(type.isInstance(b)) {
                return c.compare(type.cast(a), type.cast(b));
            } else {
                return -1;
            }
        } else {
            return type.isInstance(b) ? 1 : 0;
        }
    };
}
 
Example 38
Project: openjdk-jdk10   File: TestBCI.java   View source code 5 votes vote down vote up
Optional<SortedSet<Integer>> findLineNumbers(int value) {
    return bciToLineNumbers.entrySet().stream()
            .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
            .filter(e -> e.getKey().intValue() <= value)
            .map(Map.Entry::getValue)
            .findFirst();
}
 
Example 39
Project: underlx   File: StationPickerView.java   View source code 5 votes vote down vote up
@Override
public void sortStations(List<Station> stations) {
    final BellmanFordShortestPath<Stop, Connection> bfsp = new BellmanFordShortestPath<Stop, Connection>(network, startVertex);
    Collections.sort(stations, new Comparator<Station>() {
        @Override
        public int compare(Station station, Station t1) {
            return Double.compare(getStationWeight(station, bfsp), getStationWeight(t1, bfsp));
        }
    });

}
 
Example 40
Project: incubator-servicecomb-java-chassis   File: PerfStatMonitorMgr.java   View source code 5 votes vote down vote up
public void registerPerfStat(PerfStat perfStat, int index) {
  String name = perfStat.getName();
  PerfStatMonitor monitor = monitorMap.get(name);
  if (monitor == null) {
    monitor = new PerfStatMonitor(name, index);
    monitorMap.put(name, monitor);

    monitorList.add(monitor);

    monitorList.sort(Comparator.comparingInt(PerfStatMonitor::getIndex));
  }

  monitor.addThreadStat(perfStat);
}