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 Project: ambry   Author: linkedin   File: LatchBasedInMemoryCloudDestination.java    License: 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 Project: opencards   Author: holgerbrandl   File: CardTableRowSorter.java    License: 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 Project: SendBird-Android   Author: sendbird   File: GroupChatAdapter.java    License: 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 Project: RDFS   Author: iVCE   File: JobInProgress.java    License: 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 Project: copper-engine   Author: copper-engine   File: NonTransactionalAdapterQueue.java    License: 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 Project: SuntimesWidget   Author: forrestguice   File: WidgetThemes.java    License: 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 Project: ignite   Author: apache   File: IgniteCacheAbstractQuerySelfTest.java    License: 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 Project: AtOffer   Author: yang69   File: KLeastNumbers.java    License: 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 Project: usergrid   Author: apache   File: MultiRowColumnIterator.java    License: 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 Project: openjdk-jdk9   Author: AdoptOpenJDK   File: PrimitiveSumMinMaxTest.java    License: 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
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 Project: astor   Author: SpoonLabs   File: BaseMultiStartMultivariateRealOptimizer.java    License: 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 #13
Source Project: mycore   Author: MyCoRe-Org   File: MCRXMLFunctions.java    License: 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 #14
Source Project: cocolian-nlp   Author: cocolian   File: TFIDFKeywordExtractor.java    License: 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 #15
Source Project: codekata   Author: liupangzi   File: Solution.java    License: 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 #16
Source Project: ignite   Author: apache   File: ImputerTrainer.java    License: 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 #17
Source Project: triplea   Author: triplea-game   File: UnitTypeComparator.java    License: 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 #18
Source Project: ForgeHax   Author: fr1kin   File: Aimbot.java    License: 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 #19
Source Project: flink   Author: flink-tpc-ds   File: SortedMapTypeInfo.java    License: 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 #20
Source Project: iceberg   Author: apache   File: Comparators.java    License: 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 #21
Source Project: arcusandroid   Author: arcus-smart-home   File: CorneaUtils.java    License: 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 #22
Source Project: UTubeTV   Author: sgehrman   File: YouTubeData.java    License: 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 #23
Source Project: dekaf   Author: JetBrains   File: PostgresIntermediateProvider.java    License: 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 #24
Source Project: Kylin   Author: KylinOLAP   File: CubeDesc.java    License: 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 #25
Source Project: olat   Author: huihoo   File: UserSession.java    License: 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 #26
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: SourceReferenceUtil.java    License: 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 #27
Source Project: flink   Author: flink-tpc-ds   File: UnionStateInputFormatTest.java    License: 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 #28
Source Project: jdk8u-jdk   Author: frohoff   File: CollectionAsserts.java    License: 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 #29
Source Project: AndroidDemo   Author: maxiaozhou1234   File: CameraConfig.java    License: 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;
    }
 
Example #30
Source Project: Java8CN   Author: Java8-CNAPI-Team   File: ConcurrentSkipListMap.java    License: Apache License 2.0 5 votes vote down vote up
final KeySpliterator<K,V> keySpliterator() {
    Comparator<? super K> cmp = comparator;
    for (;;) { // ensure h corresponds to origin p
        HeadIndex<K,V> h; Node<K,V> p;
        Node<K,V> b = (h = head).node;
        if ((p = b.next) == null || p.value != null)
            return new KeySpliterator<K,V>(cmp, h, p, null, (p == null) ?
                                           0 : Integer.MAX_VALUE);
        p.helpDelete(b, p.next);
    }
}