Java Code Examples for java.util.List#sort()

The following examples show how to use java.util.List#sort() . 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: TimeBasedDataSet.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void sortTimeBasedClickStatResult(List<TimeBasedClickStatRow> returnList) {
	returnList.sort((item1, item2) -> {
       	    int cmp = item1.getClickTime().compareTo(item2.getClickTime());
       	    if (cmp == 0) {
       	    	if (item1.getDeviceClass() == item2.getDeviceClass()) {
       	    		cmp = Integer.compare(item1.getColumn_index(), item2.getColumn_index());
       	    	} else if (item1.getDeviceClass() == null) {
       	    		cmp = 1;
       	    	} else if (item2.getDeviceClass() == null) {
       	    		cmp = -1;
       	    	} else {
       	    		cmp = item1.getDeviceClass().compareTo(item2.getDeviceClass());
       	    	}
       	    }
       	    return cmp;
       	});
}
 
Example 2
Source File: CountryUtil.java    From bisq-core with GNU Affero General Public License v3.0 6 votes vote down vote up
public static List<Country> getAllCountries() {
    final Set<Country> allCountries = new HashSet<>();
    for (final Locale locale : getAllCountryLocales()) {
        String regionCode = getRegionCode(locale.getCountry());
        final Region region = new Region(regionCode, getRegionName(regionCode));
        Country country = new Country(locale.getCountry(), locale.getDisplayCountry(), region);
        if (locale.getCountry().equals("XK"))
            country = new Country(locale.getCountry(), "Republic of Kosovo", region);
        allCountries.add(country);
    }

    allCountries.add(new Country("GE", "Georgia", new Region("AS", getRegionName("AS"))));
    allCountries.add(new Country("BW", "Botswana", new Region("AF", getRegionName("AF"))));
    allCountries.add(new Country("IR", "Iran", new Region("AS", getRegionName("AS"))));

    final List<Country> allCountriesList = new ArrayList<>(allCountries);
    allCountriesList.sort((locale1, locale2) -> locale1.name.compareTo(locale2.name));
    return allCountriesList;
}
 
Example 3
Source File: InMemoryQueryEngine.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private List<T> runSorter( Query query, List<T> objects )
{
    List<T> sorted = new ArrayList<>( objects );

    sorted.sort( ( o1, o2 ) ->
    {
        for ( Order order : query.getOrders() )
        {
            int result = order.compare( o1, o2 );
            if ( result != 0 ) return result;
        }

        return 0;
    } );

    return sorted;
}
 
Example 4
Source File: RowTimeSortOperator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void onEventTime(InternalTimer<RowData, VoidNamespace> timer) throws Exception {
	long timestamp = timer.getTimestamp();

	// gets all rows for the triggering timestamps
	List<RowData> inputs = dataState.get(timestamp);
	if (inputs != null) {
		// sort rows on secondary fields if necessary
		if (comparator != null) {
			inputs.sort(comparator);
		}

		// emit rows in order
		inputs.forEach((RowData row) -> collector.collect(row));

		// remove emitted rows from state
		dataState.remove(timestamp);
		lastTriggeringTsState.update(timestamp);
	}
}
 
Example 5
Source File: ConnectionModel.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Add those {@link ValueProvider ValueProviders} to the valueprovider list that were not used so far by this
 * connection. These need to be configurable in editmode and therefore exist in the list. They will be added in
 * alphabetical order.
 */
private void setupOtherValueProviders() {
	String filter;
	try {
		filter = (location.getRepository() instanceof RemoteRepository || location.getRepository() instanceof NewVersionedRepository) ? ValueProviderHandlerRegistry.REMOTE : null;
	} catch (RepositoryException e) {
		filter = ValueProviderHandlerRegistry.REMOTE;
	}
	final List<ValueProviderModel> newValueProviders = ValueProviderHandlerRegistry.getInstance().getVisibleTypes(filter)
			.stream().filter(aType -> this.valueProviders.stream().noneMatch(vp -> aType.equals(vp.getType())))
			.map(type -> ValueProviderHandlerRegistry.getInstance().getHandler(type).createNewProvider(ConnectionI18N.getValueProviderTypeName(type)))
			.map(ValueProviderModelConverter::toModel).collect(Collectors.toList());
	if (newValueProviders.isEmpty()) {
		return;
	}
	newValueProviders.sort(Comparator.comparing(ValueProviderModel::getName));
	valueProviders.addAll(newValueProviders);
}
 
Example 6
Source File: Limelight.java    From FRC-2019-Public with MIT License 6 votes vote down vote up
/**
 * Returns raw top-left and top-right corners
 *
 * @return list of corners: index 0 - top left, index 1 - top right
 */
public static List<double[]> extractTopCornersFromBoundingBoxes(double[] xCorners, double[] yCorners) {
    List<Translation2d> corners = new ArrayList<>();
    for (int i = 0; i < xCorners.length; i++) {
        corners.add(new Translation2d(xCorners[i], yCorners[i]));
    }

    corners.sort(xSort);

    List<Translation2d> left = corners.subList(0, 4);
    List<Translation2d> right = corners.subList(4, 8);

    left.sort(ySort);
    right.sort(ySort);

    List<Translation2d> leftTop = left.subList(0, 2);
    List<Translation2d> rightTop = right.subList(0, 2);

    leftTop.sort(xSort);
    rightTop.sort(xSort);

    Translation2d leftCorner = leftTop.get(0);
    Translation2d rightCorner = rightTop.get(1);

    return List.of(new double[]{leftCorner.x(), leftCorner.y()}, new double[]{rightCorner.x(), rightCorner.y()});
}
 
Example 7
Source File: AgentStatisticsController.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/selectAgentCount", method = RequestMethod.GET, params = {"from", "to"})
@ResponseBody
public List<AgentCountStatistics> selectAgentCount(@RequestParam("from") long from, @RequestParam("to") long to) {
    Range range = Range.newRange(DateTimeUtils.timestampToStartOfDay(from), DateTimeUtils.timestampToStartOfDay(to));
    List<AgentCountStatistics> agentCountStatisticsList = agentStatisticsService.selectAgentCount(range);

    agentCountStatisticsList.sort(new Comparator<AgentCountStatistics>() {
        @Override
        public int compare(AgentCountStatistics o1, AgentCountStatistics o2) {
            if (o1.getTimestamp() > o2.getTimestamp()) {
                return -1;
            } else {
                return 1;
            }
        }
    });

    return agentCountStatisticsList;
}
 
Example 8
Source File: StrobogrammaticNumber2Test.java    From LeetCode-Sol-Res with MIT License 5 votes vote down vote up
@Test(dataProvider = "examples")
public void testFindStrobogrammatic(int n, List<String> expected) {
    StrobogrammaticNumber2 s = new StrobogrammaticNumber2();
    List<String> actual = new ArrayList<>(s.findStrobogrammatic(n));
    List<String> sortedExpected = new ArrayList<>(expected);
    actual.sort(Comparator.comparingInt(Integer::parseInt));
    sortedExpected.sort(Comparator.comparingInt(Integer::parseInt));
    Assert.assertEquals(actual, sortedExpected);
}
 
Example 9
Source File: ArrayListSortingTest.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Test
public void sortDates() {
    LocalDate ld1 = LocalDate.of(2019, 3, 1);
    LocalDate ld2 = LocalDate.of(2019, 1, 1);
    LocalDate ld3 = LocalDate.of(2019, 2, 1);
    List<LocalDate> dates = new ArrayList<>(List.of(ld1, ld2, ld3));

    dates.sort(Comparator.naturalOrder());
    assertThat(dates).containsExactly(ld2, ld3, ld1);

    dates.sort(Comparator.reverseOrder());
    assertThat(dates).containsExactly(ld1, ld3, ld2);
}
 
Example 10
Source File: ToStringDumpProcessor.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void processDump(ThreadPageLocksDumpLock snapshot) {
    sb.append("Page locks dump:").append(U.nl()).append(U.nl());

    List<ThreadState> threadStates = new ArrayList<>(snapshot.threadStates);

    // Sort thread dump by thread names.
    threadStates.sort(new Comparator<ThreadState>() {
        /** {@inheritDoc} */
        @Override public int compare(ThreadState thState1, ThreadState thState2) {
            return thState1.threadName.compareTo(thState2.threadName);
        }
    });

    for (ThreadState ths : threadStates) {
        sb.append("Thread=[name=").append(ths.threadName)
            .append(", id=").append(ths.threadId)
            .append("], state=").append(ths.state)
            .append(U.nl());

        PageLockDump pageLockDump0;

        if (ths.invalidContext == null)
            pageLockDump0 = ths.pageLockDump;
        else {
            sb.append(ths.invalidContext.msg).append(U.nl());

            pageLockDump0 = ths.invalidContext.dump;
        }

        pageLockDump0.apply(this);

        sb.append(U.nl());
    }
}
 
Example 11
Source File: QueryMetricsWriter.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
private void writeSchedulingMetrics(ClientSideMetrics clientSideMetrics) {
    this.writeBeforeSchedulingMetrics();
    List<ImmutablePair<String, SchedulingTimeSpan>> partitionSchedulingTimeSpans = clientSideMetrics.getPartitionSchedulingTimeSpans();
    partitionSchedulingTimeSpans.sort((o1, o2) -> (int) (o2.right.getResponseTime() - o1.right.getResponseTime()));
    for (ImmutablePair<String, SchedulingTimeSpan> partitionSchedulingDuration :
            partitionSchedulingTimeSpans) {
        String partitionId = partitionSchedulingDuration.getLeft();
        SchedulingTimeSpan schedulingDuration = partitionSchedulingDuration.getRight();

        this.writePartitionSchedulingDuration(partitionId, schedulingDuration);
    }

    this.writeAfterSchedulingMetrics();
}
 
Example 12
Source File: GrpcServerMetricAutoConfiguration.java    From grpc-spring-boot-starter with MIT License 5 votes vote down vote up
/**
 * Gets all method names from the given service descriptor.
 *
 * @param serviceDescriptor The service descriptor to get the names from.
 * @return The newly created and sorted list of the method names.
 */
protected List<String> collectMethodNamesForService(final ServiceDescriptor serviceDescriptor) {
    final List<String> methods = new ArrayList<>();
    for (final MethodDescriptor<?, ?> grpcMethod : serviceDescriptor.getMethods()) {
        methods.add(extractMethodName(grpcMethod));
    }
    methods.sort(String.CASE_INSENSITIVE_ORDER);
    return methods;
}
 
Example 13
Source File: Scope.java    From graphicsfuzz with Apache License 2.0 5 votes vote down vote up
public List<String> namesOfAllVariablesInScope() {
  List<String> result = new ArrayList<>();
  Scope scope = this;
  while (scope != null) {
    result.addAll(scope.keys());
    scope = scope.parent;
  }
  result.sort(String::compareTo);
  return Collections.unmodifiableList(result);
}
 
Example 14
Source File: NaiveRevisionManager.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public <T> RevisionUpdate<T> updateRevision(final RevisionClaim originalClaim, final UpdateRevisionTask<T> task) throws ExpiredRevisionClaimException {
    logger.debug("Attempting to update revision using {}", originalClaim);

    final List<Revision> revisionList = new ArrayList<>(originalClaim.getRevisions());
    revisionList.sort(new RevisionComparator());

    for (final Revision revision : revisionList) {
        final Revision currentRevision = getRevision(revision.getEntityId());
        final boolean verified = revision.equals(currentRevision);

        if (!verified) {
            // Throw an Exception indicating that we failed to obtain the locks
            throw new InvalidRevisionException("Invalid Revision was given for entity with ID '" + revision.getEntityId() + "'");
        }
    }

    // We successfully verified all revisions.
    logger.debug("Successfully verified Revision Claim for all revisions");

    // Perform the update
    final RevisionUpdate<T> updatedComponent = task.update();

    // If the update succeeded then put the updated revisions into the revisionMap
    // If an exception is thrown during the update we don't want to update revision so it is ok to bounce out of this method
    if (updatedComponent != null) {
        for (final Revision updatedRevision : updatedComponent.getUpdatedRevisions()) {
            revisionMap.put(updatedRevision.getEntityId(), updatedRevision);
        }
    }

    return updatedComponent;
}
 
Example 15
Source File: FormulaUtils.java    From mzmine2 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sort all molecular formulas by score of ppm distance, isotope sccore and msms score (with
 * weighting). Best will be at first position
 * 
 * @param list
 * @param neutralMass
 * @param ppmMax
 * @param weightIsotopeScore
 * @param weightMSMSscore
 */
public static void sortFormulaList(List<MolecularFormulaIdentity> list, double neutralMass,
    double ppmMax, double weightIsotopeScore, double weightMSMSscore) {
  if (list == null)
    return;
  list.sort(new Comparator<MolecularFormulaIdentity>() {
    @Override
    public int compare(MolecularFormulaIdentity a, MolecularFormulaIdentity b) {
      double scoreA = a.getScore(neutralMass, ppmMax, weightIsotopeScore, weightMSMSscore);
      double scoreB = b.getScore(neutralMass, ppmMax, weightIsotopeScore, weightMSMSscore);
      // best to position 0 (therefore change A B)
      return Double.compare(scoreB, scoreA);
    }
  });
}
 
Example 16
Source File: TopologicalSort.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private void sort(LinkedHashMap<ID, NodeInfo<ID, N>> nodes, List<NodeInfo<ID, N>> results) {

    while (!nodes.isEmpty()) {
      NodeInfo<ID, N> curr = removeFirstIndependent(nodes);
      if (curr != null) {
        // yay, simple. Just add the found independent node to the results.
        results.add(curr);
      } else {
        // ok, there is a cycle in the graph. Let's remove all the nodes in the first cycle we find
        // from our predecessors map, add them to the result in their original order and try to
        // continue normally

        // find the first cycle in the predecessors (in the original list order)
        Iterator<NodeInfo<ID, N>> nexts = nodes.values().iterator();
        List<NodeInfo<ID, N>> cycle;
        do {
          curr = nexts.next();
          cycle = findCycle(curr, nodes);
        } while (cycle.isEmpty() && nexts.hasNext());

        // If we ever find a graph that doesn't have any independent node, yet we fail to find a
        // cycle in it, the universe must be broken.
        if (cycle.isEmpty()) {
          throw new IllegalStateException(
              String.format(
                  "Failed to find a cycle in a graph that doesn't seem to  have any independent"
                      + " node. This should never happen. Please file a bug. Current state of the"
                      + " sorting is: nodes=%s, results=%s",
                  nodes.toString(), results.toString()));
        }

        cycle.sort(Comparator.comparingInt(a -> a.sourcePosition));

        for (NodeInfo<ID, N> n : cycle) {
          removePredecessorMapping(nodes, n);
          results.add(n);
        }
      }
    }
  }
 
Example 17
Source File: FingerprintFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void orderByChildElement(final List<Element> toSort, final String childTagName) {
    toSort.sort((a, b) -> {
        final String valueA = DomUtils.getChildText(a, childTagName);
        final String valueB = DomUtils.getChildText(b, childTagName );
        return valueA.compareTo(valueB);
    });
}
 
Example 18
Source File: Errors.java    From crate with Apache License 2.0 5 votes vote down vote up
public List<Message> getMessages() {
    if (root.errors == null) {
        return Collections.emptyList();
    }

    List<Message> result = new ArrayList<>(root.errors);
    result.sort(new Comparator<Message>() {
        @Override
        public int compare(Message a, Message b) {
            return a.getSource().compareTo(b.getSource());
        }
    });

    return unmodifiableList(result);
}
 
Example 19
Source File: TextFileInputTest.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Test
public void test_PDI17117() throws Exception {
  final String virtualFile = createVirtualFile( "pdi-14832.txt", "1,\n" );

  BaseFileField col2 = field( "col2" );
  col2.setIfNullValue( "DEFAULT" );

  TextFileInputMeta meta = createMetaObject( field( "col1" ), col2 );

  meta.inputFiles.passingThruFields = true;
  meta.inputFiles.acceptingFilenames = true;
  TextFileInputData data = createDataObject( virtualFile, ",", "col1", "col2" );

  TextFileInput input = Mockito.spy( StepMockUtil.getStep( TextFileInput.class, TextFileInputMeta.class, "test" ) );

  RowSet rowset = Mockito.mock( RowSet.class );
  RowMetaInterface rwi = Mockito.mock( RowMetaInterface.class );
  Object[] obj1 = new Object[2];
  Object[] obj2 = new Object[2];
  Mockito.doReturn( rowset ).when( input ).findInputRowSet( null );
  Mockito.doReturn( null ).when( input ).getRowFrom( rowset );
  Mockito.when( input.getRowFrom( rowset ) ).thenReturn( obj1, obj2, null );
  Mockito.doReturn( rwi ).when( rowset ).getRowMeta();
  Mockito.when( rwi.getString( obj2, 0 ) ).thenReturn( "filename1", "filename2" );
  List<Object[]> output = TransTestingUtil.execute( input, meta, data, 0, false );

  List<String> passThroughKeys = new ArrayList<>( data.passThruFields.keySet() );
  Assert.assertNotNull( passThroughKeys );
  // set order is not guaranteed - order alphabetically
  passThroughKeys.sort( String.CASE_INSENSITIVE_ORDER );
  assertEquals( 2, passThroughKeys.size() );

  Assert.assertNotNull( passThroughKeys.get( 0 ) );
  Assert.assertTrue( passThroughKeys.get( 0 ).startsWith( "0_file" ) );
  Assert.assertTrue( passThroughKeys.get( 0 ).endsWith( "filename1" ) );

  Assert.assertNotNull( passThroughKeys.get( 1 ) );
  Assert.assertTrue( passThroughKeys.get( 1 ).startsWith( "1_file" ) );
  Assert.assertTrue( passThroughKeys.get( 1 ).endsWith( "filename2" ) );

  deleteVfsFile( virtualFile );
}
 
Example 20
Source File: InMemoryStorageManager.java    From registry with Apache License 2.0 4 votes vote down vote up
@Override
public <T extends Storable> Collection<T> find(final String namespace,
                                               final List<QueryParam> queryParams,
                                               final List<OrderByField> orderByFields) throws StorageException {

    List<T> storables = new ArrayList<>();
    if (queryParams == null) {
        Collection<T> collection = list(namespace);
        storables = Lists.newArrayList(collection);
    } else {
        Class<?> clazz = nameSpaceClassMap.get(namespace);
        if (clazz != null) {
            Map<PrimaryKey, Storable> storableMap = storageMap.get(namespace);
            if (storableMap != null) {
                for (Storable val : storableMap.values()) {
                    if (matches(val, queryParams, clazz)) {
                        storables.add((T) val);
                    }
                }
            }
        }
    }

    if (orderByFields != null && !orderByFields.isEmpty()) {
        storables.sort((storable1, storable2) -> {
            try {
                for (OrderByField orderByField : orderByFields) {
                    Comparable value1 = ReflectionHelper.invokeGetter(orderByField.getFieldName(), storable1);
                    Comparable value2 = ReflectionHelper.invokeGetter(orderByField.getFieldName(), storable2);
                    int compareTo;
                    // same values continue
                    if(value1 == value2) {
                        continue;
                    } else if(value1 == null) {
                        // value2 is non null
                        compareTo = -1;
                    } else if(value2 == null) {
                        // value1 is non null
                        compareTo = 1;
                    } else {
                        // both value and value2 non null
                        compareTo = value1.compareTo(value2);
                    }

                    if (compareTo == 0) {
                        continue;
                    }
                    return orderByField.isDescending() ? -compareTo : compareTo;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            // all group by fields are matched means equal
            return 0;
        });
    }

    return storables;
}