java.util.Comparator Java Examples

The following examples show how to use java.util.Comparator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LatchBasedInMemoryCloudDestination.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Populates an ordered sequenced list of blobs in the specified partition in {@code nextEntries} {@link List},
 * ordered by update time of blobs. Returns the updated {@link com.github.ambry.replication.FindToken}.
 * @param partitionPath the partition to query.
 * @param findToken the {@link com.github.ambry.replication.FindToken} specifying the boundary for the query.
 * @param maxTotalSizeOfEntries the cumulative size limit for the list of blobs returned.
 * @return {@link FindResult} instance that contains updated {@link CosmosUpdateTimeFindToken} object which can act as a bookmark for
 * subsequent requests, and {@link List} of {@link CloudBlobMetadata} entries.
 * @throws CloudStorageException
 */
private FindResult findUpdateTimeBasedEntries(String partitionPath, FindToken findToken, long maxTotalSizeOfEntries) {
  List<CloudBlobMetadata> nextEntries = new ArrayList<>();
  CosmosUpdateTimeFindToken cosmosUpdateTimeFindToken = (CosmosUpdateTimeFindToken) findToken;
  List<CloudBlobMetadata> entries = new LinkedList<>();
  for (BlobId blobId : map.keySet()) {
    if (map.get(blobId).getFirst().getLastUpdateTime() >= cosmosUpdateTimeFindToken.getLastUpdateTime()) {
      if (cosmosUpdateTimeFindToken.getLastUpdateTimeReadBlobIds().contains(map.get(blobId).getFirst().getId())) {
        continue;
      }
      entries.add(map.get(blobId).getFirst());
    }
  }
  Collections.sort(entries, Comparator.comparingLong(CloudBlobMetadata::getLastUpdateTime));

  List<CloudBlobMetadata> cappedRsults = CloudBlobMetadata.capMetadataListBySize(entries, maxTotalSizeOfEntries);
  nextEntries.addAll(cappedRsults);
  return new FindResult(nextEntries,
      CosmosUpdateTimeFindToken.getUpdatedToken(cosmosUpdateTimeFindToken, cappedRsults));
}
 
Example #2
Source File: CardTableRowSorter.java    From opencards with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public CardTableRowSorter(CardTableModel model) {
    super(model);

    // define the different column comparators

    // skip the name row because the default sorter does a great job here
    setComparator(1, new Comparator<StringifiedScheduleDate>() {
        public int compare(StringifiedScheduleDate o1, StringifiedScheduleDate o2) {
            return o1.compareTo(o2);
        }
    });

    setComparator(2, new IntegerComparator());
    setComparator(3, new IntegerComparator());

    // apply the default sorting

    List<SortKey> sortKeys = new ArrayList<SortKey>();
    sortKeys.add(new RowSorter.SortKey(0, SortOrder.ASCENDING));
    setSortKeys(sortKeys);
    sort();
}
 
Example #3
Source File: GroupChatAdapter.java    From SendBird-Android with MIT License 6 votes vote down vote up
public void insertFailedMessages(List<BaseMessage> messages) {
    synchronized (mFailedMessageList) {
        for (BaseMessage message : messages) {
            String requestId = getRequestId(message);
            if (requestId.isEmpty()) {
                continue;
            }

            mResendingMessageSet.add(requestId);
            mFailedMessageList.add(message);
        }

        Collections.sort(mFailedMessageList, new Comparator<BaseMessage>() {
            @Override
            public int compare(BaseMessage m1, BaseMessage m2) {
                long x = m1.getCreatedAt();
                long y = m2.getCreatedAt();

                return (x < y) ? 1 : ((x == y) ? 0 : -1);
            }
        });
    }

    notifyDataSetChanged();
}
 
Example #4
Source File: JobInProgress.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Given a candidate set of tasks, find and order the ones that
 * can be speculated and return the same.
 */
protected synchronized List<TaskInProgress> findSpeculativeTaskCandidates
  (Collection<TaskInProgress> list) {
  ArrayList<TaskInProgress> candidates = new ArrayList<TaskInProgress>();

  long now = JobTracker.getClock().getTime();
  Iterator<TaskInProgress> iter = list.iterator();
  while (iter.hasNext()) {
    TaskInProgress tip = iter.next();
    if (tip.canBeSpeculated(now)) {
      candidates.add(tip);
    }
  }
  if (candidates.size() > 0 ) {
    Comparator<TaskInProgress> LateComparator =
      new EstimatedTimeLeftComparator(now);

    Collections.sort(candidates, LateComparator);
  }
  return candidates;
}
 
Example #5
Source File: NonTransactionalAdapterQueue.java    From copper-engine with Apache License 2.0 6 votes vote down vote up
public NonTransactionalAdapterQueue(Collection<String> adapterIds, AdapterCallPersisterFactory persistence, int transientQueueLength, int triggerReloadQueueLength, TransactionController ctrl, Batcher batcher) {
    this.transientQueueLength = transientQueueLength;
    this.triggerReloadQueueLength = triggerReloadQueueLength;
    this.persistence = persistence;
    this.adapterIds = new ArrayList<String>(adapterIds);
    this.ctrl = ctrl;
    this.batcher = batcher;
    this.queue = new PriorityBlockingQueue<AdapterCall>(transientQueueLength, new Comparator<AdapterCall>() {

        @Override
        public int compare(AdapterCall o1, AdapterCall o2) {
            if (o1.getPriority() < o2.getPriority())
                return -1;
            if (o1.getPriority() > o2.getPriority())
                return 1;
            return 0;
        }

    });
    this.reloadThread = new ReloadThread();
}
 
Example #6
Source File: WidgetThemes.java    From SuntimesWidget with GNU General Public License v3.0 6 votes vote down vote up
public static List<ThemeDescriptor> getSortedValues(final boolean defaultsFirst)
{
    List<SuntimesTheme.ThemeDescriptor> themeDefs = getValues();
    Collections.sort(themeDefs, new Comparator<ThemeDescriptor>()
    {
        @Override
        public int compare(SuntimesTheme.ThemeDescriptor o1, SuntimesTheme.ThemeDescriptor o2)
        {
            if (defaultsFirst)
            {
                if (o1.isDefault() && !o2.isDefault())
                    return -1;
                else if (o2.isDefault() && !o1.isDefault())
                    return 1;
            }
            return o1.displayString().compareToIgnoreCase(o2.displayString());
        }
    });
    return themeDefs;
}
 
Example #7
Source File: IgniteCacheAbstractQuerySelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param cache Ignite cache.
 * @throws Exception If failed.
 */
private void testPaginationGet(IgniteCache<Integer, Integer> cache) throws Exception {
    for (int i = 0; i < 50; i++)
        cache.put(i, i);

    QueryCursor<Cache.Entry<Integer, Integer>> q =
        cache.query(new SqlQuery<Integer, Integer>(Integer.class, "_key >= 0"));

    List<Cache.Entry<Integer, Integer>> list = new ArrayList<>(q.getAll());

    Collections.sort(list, new Comparator<Cache.Entry<Integer, Integer>>() {
        @Override public int compare(Cache.Entry<Integer, Integer> e1, Cache.Entry<Integer, Integer> e2) {
            return e1.getKey().compareTo(e2.getKey());
        }
    });

    for (int i = 0; i < 50; i++) {
        Cache.Entry<Integer, Integer> e = list.get(i);

        assertEquals(i, (int)e.getKey());
        assertEquals(i, (int)e.getValue());
    }
}
 
Example #8
Source File: KLeastNumbers.java    From AtOffer with Apache License 2.0 6 votes vote down vote up
/**
 * O(nlogk)的算法,特别适合处理海量数据
 * 基于堆或者红黑树
 * @param array
 * @param k
 * @return
 */
public ArrayList<Integer> getLeastNumbers(int[] array, int k) {
    if(array == null || array.length == 0 || k > array.length || k <= 0) {
        return new ArrayList<>();
    }
    PriorityQueue<Integer> kLeastNumbers = new PriorityQueue<>(k, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2.compareTo(o1);
        }
    });
    for (int i = 0; i < array.length; i++) {
        if(kLeastNumbers.size() < k) {
            kLeastNumbers.offer(array[i]);
        } else {
            if(kLeastNumbers.peek() > array[i]) {
                kLeastNumbers.poll();
                kLeastNumbers.offer(array[i]);
            }
        }
    }
    return new ArrayList<>(kLeastNumbers);
}
 
Example #9
Source File: MultiRowColumnIterator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * Create the iterator
 */
public MultiRowColumnIterator( final Keyspace keyspace, final ColumnFamily<R, C> cf,
                               final ConsistencyLevel consistencyLevel, final ColumnParser<C, T> columnParser,
                               final ColumnSearch<T> columnSearch, final Comparator<T> comparator,
                               final Collection<R> rowKeys, final int pageSize ) {
    this.cf = cf;
    this.pageSize = pageSize;
    this.columnParser = columnParser;
    this.columnSearch = columnSearch;
    this.comparator = comparator;
    this.rowKeys = rowKeys;
    this.keyspace = keyspace;
    this.consistencyLevel = consistencyLevel;
    this.moreToReturn = true;

    //        seenResults = new HashMap<>( pageSize * 10 );
}
 
Example #10
Source File: PrimitiveSumMinMaxTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void testBooleanMethods() {
    BinaryOperator<Boolean> and = Boolean::logicalAnd;
    BinaryOperator<Boolean> or = Boolean::logicalOr;
    BinaryOperator<Boolean> xor = Boolean::logicalXor;
    Comparator<Boolean> cmp = Boolean::compare;

    assertTrue(and.apply(true, true));
    assertFalse(and.apply(true, false));
    assertFalse(and.apply(false, true));
    assertFalse(and.apply(false, false));

    assertTrue(or.apply(true, true));
    assertTrue(or.apply(true, false));
    assertTrue(or.apply(false, true));
    assertFalse(or.apply(false, false));

    assertFalse(xor.apply(true, true));
    assertTrue(xor.apply(true, false));
    assertTrue(xor.apply(false, true));
    assertFalse(xor.apply(false, false));

    assertEquals(Boolean.TRUE.compareTo(Boolean.TRUE), cmp.compare(true, true));
    assertEquals(Boolean.TRUE.compareTo(Boolean.FALSE), cmp.compare(true, false));
    assertEquals(Boolean.FALSE.compareTo(Boolean.TRUE), cmp.compare(false, true));
    assertEquals(Boolean.FALSE.compareTo(Boolean.FALSE), cmp.compare(false, false));
}
 
Example #11
Source File: TimerExpiredTaskApplicationStubs.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private ProcessStubs concreteProcessStubs(Business business, DateRange dateRange, ApplicationStub applicationStub)
		throws Exception {
	Set<String> ids = new HashSet<>();
	ids.addAll(this.listProcessFromTask(business, dateRange, applicationStub));
	ids.addAll(this.listProcessFromTaskCompleted(business, dateRange, applicationStub));
	List<ProcessStub> list = new ArrayList<>();
	for (String str : ids) {
		String name = this.getProcessName(business, dateRange, str);
		ProcessStub stub = new ProcessStub();
		stub.setName(name);
		stub.setValue(str);
		stub.setApplicationCategory(applicationStub.getCategory());
		stub.setApplicationName(applicationStub.getName());
		stub.setApplicationValue(applicationStub.getValue());
		stub.setActivityStubs(this.concreteActivityStubs(business, dateRange, stub));
		list.add(stub);
	}
	list = list.stream()
			.sorted(Comparator.comparing(ProcessStub::getName, Comparator.nullsLast(String::compareTo)))
			.collect(Collectors.toList());
	ProcessStubs stubs = new ProcessStubs();
	stubs.addAll(list);
	return stubs;
}
 
Example #12
Source File: Utils.java    From fabric-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Generate hash of a chaincode directory
 *
 * @param rootDir      Root directory
 * @param chaincodeDir Channel code directory
 * @param hash         Previous hash (if any)
 * @return hash of the directory
 * @throws IOException
 */
public static String generateDirectoryHash(String rootDir, String chaincodeDir, String hash) throws IOException {
    // Generate the project directory
    Path projectPath = null;
    if (rootDir == null) {
        projectPath = Paths.get(chaincodeDir);
    } else {
        projectPath = Paths.get(rootDir, chaincodeDir);
    }

    File dir = projectPath.toFile();
    if (!dir.exists() || !dir.isDirectory()) {
        throw new IOException(format("The chaincode path \"%s\" is invalid", projectPath));
    }

    StringBuilder hashBuilder = new StringBuilder(hash);
    Files.walk(projectPath)
            .sorted(Comparator.naturalOrder())
            .filter(Files::isRegularFile)
            .map(Path::toFile)
            .forEach(file -> {
                try {
                    byte[] buf = readFile(file);
                    byte[] toHash = Arrays.concatenate(buf, hashBuilder.toString().getBytes(UTF_8));
                    hashBuilder.setLength(0);
                    hashBuilder.append(Hex.toHexString(hash(toHash, new SHA3Digest())));
                } catch (IOException ex) {
                    throw new RuntimeException(format("Error while reading file %s", file.getAbsolutePath()), ex);
                }
            });

    // If original hash and final hash are the same, it indicates that no new contents were found
    if (hashBuilder.toString().equals(hash)) {
        throw new IOException(format("The chaincode directory \"%s\" has no files", projectPath));
    }
    return hashBuilder.toString();
}
 
Example #13
Source File: BaseMultiStartMultivariateRealOptimizer.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sort the optima from best to worst, followed by {@code null} elements.
 *
 * @param goal Goal type.
 */
private void sortPairs(final GoalType goal) {
    Arrays.sort(optima, new Comparator<RealPointValuePair>() {
            public int compare(final RealPointValuePair o1,
                               final RealPointValuePair o2) {
                if (o1 == null) {
                    return (o2 == null) ? 0 : 1;
                } else if (o2 == null) {
                    return -1;
                }
                final double v1 = o1.getValue();
                final double v2 = o2.getValue();
                return (goal == GoalType.MINIMIZE) ?
                    Double.compare(v1, v2) : Double.compare(v2, v1);
            }
        });
}
 
Example #14
Source File: MCRXMLFunctions.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This only works with text nodes
 * @param nodes
 * @return the order of nodes maybe changes
 */
public static NodeList distinctValues(NodeList nodes) {
    SortedSet<Node> distinctNodeSet = new TreeSet<>(new Comparator<Node>() {
        @Override
        public int compare(Node node, Node t1) {
            String nodeValue = node.getNodeValue();
            String nodeValue1 = t1.getNodeValue();
            return Objects.equals(nodeValue1, nodeValue) ? 0 : -1;
        }
    });
    for (int i = 0; i < nodes.getLength(); i++) {
        distinctNodeSet.add(nodes.item(i));
    }

    return new SetNodeList(distinctNodeSet);
}
 
Example #15
Source File: TFIDFKeywordExtractor.java    From cocolian-nlp with Apache License 2.0 6 votes vote down vote up
/**
 * 获取从map中获取Top N 个关键字
 * @param keywords
 * @param count
 * @return
 */
private List<String> extractTopN(Map<String, Integer> keywords, int count) {
	if (count > keywords.size())
		count = keywords.size();
	List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(
			keywords.entrySet());
	Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

		@Override
		public int compare(Entry<String, Integer> o1,
				Entry<String, Integer> o2) {
			return o2.getValue() - o1.getValue();
		}
	});
	List<String> result = new ArrayList<String>();
	for (Map.Entry<String, Integer> entry : list.subList(0, count)) {
		result.add(entry.getKey());
	}
	return result;
}
 
Example #16
Source File: Solution.java    From codekata with MIT License 6 votes vote down vote up
public String reorganizeString(String S) {
    int[][] table = new int[26][2];
    for (int i = 0; i < S.length(); i++) table[S.charAt(i) - 'a'][1]++;
    for (int i = 0; i < 26; i++) table[i][0] = i;

    Arrays.sort(table, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[1] == o1[1] ? o1[0] - o2[0] : o2[1] - o1[1];
        }
    });
    if (table[0][1] > (S.length() + 1) / 2) return "";

    char[] tmp = new char[S.length()];
    int cursor = 0;
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < table[i][1]; j++) {
            if (cursor >= tmp.length) cursor = 1;
            tmp[cursor] = (char) (table[i][0] + 'a');
            cursor += 2;
        }
    }
    return new String(tmp);
}
 
Example #17
Source File: ImputerTrainer.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the imputing values by frequencies keeping in the given dataset.
 *
 * @param dataset The dataset of frequencies for each feature aggregated in each partition..
 * @return Most frequent value for each feature.
 */
private double[] calculateImputingValuesByTheMostFrequentValues(
    Dataset<EmptyContext, ImputerPartitionData> dataset) {
    Map<Double, Integer>[] frequencies = getAggregatedFrequencies(dataset);

    double[] res = new double[frequencies.length];

    for (int i = 0; i < frequencies.length; i++) {
        Optional<Map.Entry<Double, Integer>> max = frequencies[i].entrySet()
            .stream()
            .max(Comparator.comparingInt(Map.Entry::getValue));

        if (max.isPresent())
            res[i] = max.get().getKey();
    }

    return res;
}
 
Example #18
Source File: UnitTypeComparator.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int compare(final UnitType u1, final UnitType u2) {
  return Comparator.<UnitType, UnitAttachment>comparing(
          UnitAttachment::get, Comparator.comparing(UnitAttachment::getIsInfrastructure))
      .thenComparing(Matches.unitTypeIsAaForAnything()::test)
      .thenComparing(
          UnitAttachment::get,
          Comparator.comparing(UnitAttachment::getIsAir)
              .thenComparing(UnitAttachment::getIsSea)
              .thenComparingInt(UnitAttachment::getAttack))
      .thenComparing(NamedAttachable::getName)
      .compare(u1, u2);
}
 
Example #19
Source File: Aimbot.java    From ForgeHax with MIT License 5 votes vote down vote up
private Entity findTarget(final Vec3d pos, final Vec3d viewNormal, final Angle angles) {
  return getWorld()
      .loadedEntityList
      .stream()
      .filter(entity -> filterTarget(pos, viewNormal, angles, entity))
      .min(Comparator.comparingDouble(entity -> selecting(pos, viewNormal, angles, entity)))
      .orElse(null);
}
 
Example #20
Source File: SortedMapTypeInfo.java    From flink with Apache License 2.0 5 votes vote down vote up
public SortedMapTypeInfo(
		TypeInformation<K> keyTypeInfo,
		TypeInformation<V> valueTypeInfo,
		Comparator<K> comparator) {
	super(keyTypeInfo, valueTypeInfo);

	Preconditions.checkNotNull(comparator, "The comparator cannot be null.");
	this.comparator = comparator;
}
 
Example #21
Source File: Comparators.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Comparator<T> forType(Type.PrimitiveType type) {
  Comparator<?> cmp = COMPARATORS.get(type);
  if (cmp != null) {
    return (Comparator<T>) cmp;
  } else if (type instanceof Types.FixedType) {
    return (Comparator<T>) Comparators.unsignedBytes();
  } else if (type instanceof Types.DecimalType) {
    return (Comparator<T>) Comparator.naturalOrder();
  }

  throw new UnsupportedOperationException("Cannot determine comparator for type: " + type);
}
 
Example #22
Source File: CorneaUtils.java    From arcusandroid with Apache License 2.0 5 votes vote down vote up
@NonNull
public static List<PersonModel> sortPeopleByDisplayName (@NonNull List<PersonModel> people) {
    List<PersonModel> sortedPeople = new ArrayList<>(people);

    Collections.sort(sortedPeople, new Comparator<PersonModel>() {
        @Override
        public int compare(@NonNull PersonModel lhs, @NonNull PersonModel rhs) {
            return CorneaUtils.getPersonDisplayName(lhs).toUpperCase().compareTo(CorneaUtils.getPersonDisplayName(rhs).toUpperCase());
        }
    });

    return sortedPeople;
}
 
Example #23
Source File: YouTubeData.java    From UTubeTV with The Unlicense 5 votes vote down vote up
public static List<YouTubeData> sortByTitle(List<YouTubeData> videoIDs) {
  Collections.sort(videoIDs, new Comparator<YouTubeData>() {
    public int compare(YouTubeData lhs, YouTubeData rhs) {
      return lhs.mTitle.compareTo(rhs.mTitle);
    }
  });

  return videoIDs;
}
 
Example #24
Source File: PostgresIntermediateProvider.java    From dekaf with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
protected Comparator<Driver> getDriverComparator() {
  return new Comparator<Driver>() {
    @Override
    public int compare(Driver firstDriver, Driver secondDriver) {
      String firstDriverName = firstDriver.getClass().getName();
      String secondDriverName = secondDriver.getClass().getName();
      return firstDriverName.contains("postgres") ? -1 :
             secondDriverName.contains("postgres") ? 1 :
             0;
    }
  };
}
 
Example #25
Source File: CubeDesc.java    From Kylin with Apache License 2.0 5 votes vote down vote up
private void sortHierarchiesByLevel(HierarchyDesc[] hierarchies) {
    if (hierarchies != null) {
        Arrays.sort(hierarchies, new Comparator<HierarchyDesc>() {
            @Override
            public int compare(HierarchyDesc h1, HierarchyDesc h2) {
                Integer level1 = Integer.parseInt(h1.getLevel());
                Integer level2 = Integer.parseInt(h2.getLevel());
                return level1.compareTo(level2);
            }
        });
    }
}
 
Example #26
Source File: UserSession.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Invalidate a given number of oldest (last-click-time) sessions except admin-sessions.
 * 
 * @param nbrSessions
 *            number of sessions whisch will be invalidated
 * @return Number of invalidated sessions.
 */
public static int invalidateOldestSessions(int nbrSessions) {
    int invalidateCounter = 0;
    // 1. Copy authUserSessions in sorted TreeMap
    // This is the Comparator that will be used to sort the TreeSet:
    Comparator<UserSession> sessionComparator = new Comparator<UserSession>() {
        @Override
        public int compare(UserSession o1, UserSession o2) {
            Long long1 = new Long(o1.getSessionInfo().getLastClickTime());
            Long long2 = new Long(o2.getSessionInfo().getLastClickTime());
            return long1.compareTo(long2);
        }
    };
    // clusterNOK ?? invalidate only locale sessions ?
    TreeSet<UserSession> sortedSet = new TreeSet<UserSession>(sessionComparator);
    sortedSet.addAll(authUserSessions);
    int i = 0;
    for (Iterator<UserSession> iterator = sortedSet.iterator(); iterator.hasNext() && i++ < nbrSessions;) {
        try {
            UserSession userSession = (UserSession) iterator.next();
            if (!userSession.getRoles().isOLATAdmin() && !userSession.getSessionInfo().isWebDAV()) {
                userSession.signOffAndClear();
                invalidateCounter++;
            }
        } catch (Throwable th) {
            log.warn("Error signOffAndClear ", th);
        }
    }
    return invalidateCounter;
}
 
Example #27
Source File: SourceReferenceUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ISourceReference[] sortByOffset(ISourceReference[] methods){
	Arrays.sort(methods, new Comparator<ISourceReference>(){
		public int compare(ISourceReference o1, ISourceReference o2){
			try{
				return o2.getSourceRange().getOffset() - o1.getSourceRange().getOffset();
			} catch (JavaModelException e){
				return o2.hashCode() - o1.hashCode();
			}
		}
	});
	return methods;
}
 
Example #28
Source File: UnionStateInputFormatTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadUnionOperatorState() throws Exception {
	try (OneInputStreamOperatorTestHarness<Integer, Void> testHarness = getTestHarness()) {
		testHarness.open();

		testHarness.processElement(1, 0);
		testHarness.processElement(2, 0);
		testHarness.processElement(3, 0);

		OperatorSubtaskState subtaskState = testHarness.snapshot(0, 0);
		OperatorState state = new OperatorState(OperatorIDGenerator.fromUid("uid"), 1, 4);
		state.putState(0, subtaskState);

		OperatorStateInputSplit split = new OperatorStateInputSplit(subtaskState.getManagedOperatorState(), 0);

		UnionStateInputFormat<Integer> format = new UnionStateInputFormat<>(state, descriptor);

		format.setRuntimeContext(new MockStreamingRuntimeContext(false, 1, 0));
		format.open(split);

		List<Integer> results = new ArrayList<>();

		while (!format.reachedEnd()) {
			results.add(format.nextRecord(0));
		}

		results.sort(Comparator.naturalOrder());

		Assert.assertEquals("Failed to read correct list state from state backend", Arrays.asList(1, 2, 3), results);
	}
}
 
Example #29
Source File: CollectionAsserts.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static<T> void assertSorted(Iterator<T> i, Comparator<? super T> comp) {
    if (!i.hasNext())
        return;
    T last = i.next();
    while (i.hasNext()) {
        T t = i.next();
        assertTrue(comp.compare(last, t) <= 0);
        assertTrue(comp.compare(t, last) >= 0);
        last = t;
    }
}
 
Example #30
Source File: CameraConfig.java    From AndroidDemo with MIT License 5 votes vote down vote up
private Size calculationSize(StreamConfigurationMap map) {
        if (map != null) {
            return Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                    new Comparator<Size>() {
                        @Override
                        public int compare(Size lhs, Size rhs) {
//                            return Long.signum((long) rhs.getWidth() * rhs.getHeight() -
//                                    (long) lhs.getWidth() * lhs.getHeight());
                            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                                    (long) rhs.getWidth() * rhs.getHeight());
                        }
                    });
        }
        return null;
    }