当前位置: 首页>>代码示例>>Java>>正文


Java List.sort方法代码示例

本文整理汇总了Java中java.util.List.sort方法的典型用法代码示例。如果您正苦于以下问题:Java List.sort方法的具体用法?Java List.sort怎么用?Java List.sort使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.List的用法示例。


在下文中一共展示了List.sort方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getNewPostsOfPage

import java.util.List; //导入方法依赖的package包/类
private List<Post> getNewPostsOfPage(int page, Set<Long> ids) throws PageNotFoundException {
    if (page > 0 && ids.isEmpty()) {
        throw new PageNotFoundException();
    }

    List<Post> posts = new ArrayList<>();

    if (page < MAX_CACHE_POST_PAGES) {
        for (Long id : ids) {
            posts.add(postService.getPost(id));
        }
    } else {
        posts = postRepository.findByIdIn(ids);
        posts.sort((o1, o2) -> {
            double diff = o2.getShareAt().toEpochSecond() - o1.getShareAt().toEpochSecond();
            return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
        });
    }

    return posts;
}
 
开发者ID:ugouku,项目名称:shoucang,代码行数:22,代码来源:PostListService.java

示例2: testSuggestionOrdering

import java.util.List; //导入方法依赖的package包/类
public void testSuggestionOrdering() throws Exception {
    List<Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>> suggestions;
    suggestions = new ArrayList<>();
    int n = randomIntBetween(2, 5);
    for (int i = 0; i < n; i++) {
        suggestions.add(new CompletionSuggestion(randomAsciiOfLength(10), randomIntBetween(3, 5)));
    }
    Collections.shuffle(suggestions, random());
    Suggest suggest = new Suggest(suggestions);
    List<Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>>> sortedSuggestions;
    sortedSuggestions = new ArrayList<>(suggestions);
    sortedSuggestions.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    List<CompletionSuggestion> completionSuggestions = suggest.filter(CompletionSuggestion.class);
    assertThat(completionSuggestions.size(), equalTo(n));
    for (int i = 0; i < n; i++) {
        assertThat(completionSuggestions.get(i).getName(), equalTo(sortedSuggestions.get(i).getName()));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:SuggestTests.java

示例3: sortByAllFields

import java.util.List; //导入方法依赖的package包/类
/**
 * Sorting List<User> with Comparator by name and age.
 * @param list original List<User>
 * @return sorted list.
 */
public List<User> sortByAllFields(List<User> list) {

    list.sort(new Comparator<User>() {
        @Override
        public int compare(User o1, User o2) {
            int result = 0;
            if (o1 != null && o2 != null) {
                result = o1.getName().compareTo(o2.getName());
                if (result == 0) {
                    result = o1.getAge() - o2.getAge();
                }
            } else if (o1 != null) {
                result = 1;
            } else if (o2 != null) {
                result = -1;
            }
            return result;
        }
    });
    return list;
}
 
开发者ID:PavelZubaha,项目名称:pzubaha,代码行数:27,代码来源:UserSort.java

示例4: findMeeCreeps

import java.util.List; //导入方法依赖的package包/类
private boolean findMeeCreeps() {
    IMeeCreep entity = helper.getMeeCreep();
    BlockPos position = entity.getEntity().getPosition();
    List<EntityMeeCreeps> meeCreeps = entity.getWorld().getEntitiesWithinAABB(EntityMeeCreeps.class, getSearchBox(),
            input -> input != entity.getEntity());
    if (!meeCreeps.isEmpty()) {
        meeCreeps.sort((o1, o2) -> {
            double d1 = position.distanceSq(o1.posX, o1.posY, o1.posZ);
            double d2 = position.distanceSq(o2.posX, o2.posY, o2.posZ);
            return Double.compare(d1, d2);
        });
        EntityMeeCreeps enemy = meeCreeps.get(0);
        helper.navigateTo(enemy, (pos) -> attack(enemy));
        return true;
    }
    return false;
}
 
开发者ID:McJty,项目名称:MeeCreeps,代码行数:18,代码来源:AngryActionWorker.java

示例5: listAllEntities

import java.util.List; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
protected List<TestEntity> listAllEntities(int startIndex, int maxResultCount) {
	List<TestEntity> entityList = new ArrayList<TestEntity>(entities.values());
	entityList.sort(Comparator.comparingLong(TestEntity::getId));
	int start = 0;
	if (startIndex >= 0) {
		start = startIndex;
	}
	int end = entityList.size();
	if (maxResultCount >= 0) {
		end = Math.min(entityList.size(), start + maxResultCount);
	}
	entityList = entityList.subList(start, end);
	return entityList;
}
 
开发者ID:DescartesResearch,项目名称:Pet-Supply-Store,代码行数:19,代码来源:TestEntityEndpoint.java

示例6: fillInPlainTextElement

import java.util.List; //导入方法依赖的package包/类
/**
 * The content not matched in rawPattern will be printed as it is, so should be converted to {@link PlainTextElement}
 * @param rawPattern
 * @param extractionList
 */
private void fillInPlainTextElement(String rawPattern, List<AccessLogElementExtraction> extractionList) {
  int cursor = 0;
  List<AccessLogElementExtraction> plainTextExtractionList = new ArrayList<>();
  for (AccessLogElementExtraction extraction : extractionList) {
    if (cursor < extraction.getStart()) {
      plainTextExtractionList.add(
          new AccessLogElementExtraction()
              .setStart(cursor)
              .setEnd(extraction.getStart())
              .setAccessLogElement(
                  new PlainTextElement(rawPattern.substring(cursor, extraction.getStart()))));
    }
    cursor = extraction.getEnd();
  }

  extractionList.addAll(plainTextExtractionList);
  extractionList.sort(ACCESS_LOG_ELEMENT_EXTRACTION_COMPARATOR);
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:24,代码来源:DefaultAccessLogPatternParser.java

示例7: getSortedModuleArray

import java.util.List; //导入方法依赖的package包/类
private static List<Module> getSortedModuleArray() {
    final List<Module> list = new ArrayList<Module>();
    for (final Module mod : ModuleManager.moduleList) {
        if (mod.enabled) {
            if (!mod.shown) {
                continue;
            }
            list.add(mod);
        }
    }
    list.sort(new Comparator<Module>() {
        @Override
        public int compare(final Module m1, final Module m2) {
            final String s1 = String.valueOf(m1.name) + ((m1.suffix == null) ? "" : m1.suffix);
            final String s2 = String.valueOf(m2.name) + ((m2.suffix == null) ? "" : m2.suffix);
            final int cmp = Client.font.getStringWidth(s2) - Client.font.getStringWidth(s1);
            return (cmp != 0) ? cmp : s2.compareTo(s1);
        }
    });
    return list;
}
 
开发者ID:SkidJava,项目名称:BaseClient,代码行数:22,代码来源:HUD.java

示例8: findSpotToFlatten

import java.util.List; //导入方法依赖的package包/类
/**
 * Returns absolute position
 */
private BlockPos findSpotToFlatten() {
    IMeeCreep entity = helper.getMeeCreep();
    BlockPos tpos = options.getTargetPos();
    int hs = (getSize() - 1) / 2;

    List<BlockPos> todo = new ArrayList<>();
    for (int x = -hs; x <= hs; x++) {
        for (int y = 1; y <= 5; y++) {
            for (int z = -hs; z <= hs; z++) {
                BlockPos relativePos = new BlockPos(x, y, z);
                BlockPos p = tpos.add(relativePos);
                if (!entity.getWorld().isAirBlock(p) && !positionsToSkip.contains(p)) {
                    todo.add(p);
                }
            }
        }
    }
    if (todo.isEmpty()) {
        return null;
    }

    BlockPos position = entity.getEntity().getPosition();
    todo.sort((o1, o2) -> {
        double d1 = position.distanceSq(o1);
        double d2 = position.distanceSq(o2);
        return Double.compare(d1, d2);
    });
    return todo.get(0);
}
 
开发者ID:McJty,项目名称:MeeCreeps,代码行数:33,代码来源:FlattenAreaActionWorker.java

示例9: collides

import java.util.List; //导入方法依赖的package包/类
@Override
public Point2D collides(final Line2D rayCast) {
  final Point2D rayCastSource = new Point2D.Double(rayCast.getX1(), rayCast.getY1());
  final List<Rectangle2D> collBoxes = this.getAllCollisionBoxes();
  collBoxes.sort((rect1, rect2) -> {
    final Point2D rect1Center = new Point2D.Double(rect1.getCenterX(), rect1.getCenterY());
    final Point2D rect2Center = new Point2D.Double(rect2.getCenterX(), rect2.getCenterY());
    final double dist1 = rect1Center.distance(rayCastSource);
    final double dist2 = rect2Center.distance(rayCastSource);

    if (dist1 < dist2) {
      return -1;
    }

    if (dist1 > dist2) {
      return 1;
    }

    return 0;
  });

  for (final Rectangle2D collisionBox : collBoxes) {
    if (collisionBox.intersectsLine(rayCast)) {
      double closestDist = -1;
      Point2D closestPoint = null;
      for (final Point2D intersection : GeometricUtilities.getIntersectionPoints(rayCast, collisionBox)) {
        final double dist = intersection.distance(rayCastSource);
        if (closestPoint == null || dist < closestDist) {
          closestPoint = intersection;
          closestDist = dist;
        }
      }

      return closestPoint;
    }
  }

  return null;
}
 
开发者ID:gurkenlabs,项目名称:litiengine,代码行数:40,代码来源:PhysicsEngine.java

示例10: getSortedFlows

import java.util.List; //导入方法依赖的package包/类
/**
 * Returns the list of devices sorted using the device ID URIs.
 *
 * @param deviceService device service
 * @param service flow rule service
 * @param coreService core service
 * @return sorted device list
 */
protected SortedMap<Device, List<FlowEntry>> getSortedFlows(DeviceService deviceService,
                                                      FlowRuleService service, CoreService coreService) {
    SortedMap<Device, List<FlowEntry>> flows = new TreeMap<>(Comparators.ELEMENT_COMPARATOR);
    List<FlowEntry> rules;

    Iterable<Device> devices = null;
    if (uri == null) {
        devices = deviceService.getDevices();
    } else {
        Device dev = deviceService.getDevice(DeviceId.deviceId(uri));
        devices = (dev == null) ? deviceService.getDevices()
                                : Collections.singletonList(dev);
    }

    for (Device d : devices) {
        if (predicate.equals(TRUE_PREDICATE)) {
            rules = newArrayList(service.getFlowEntries(d.id()));
        } else {
            rules = newArrayList();
            for (FlowEntry f : service.getFlowEntries(d.id())) {
                if (predicate.test(f)) {
                    rules.add(f);
                }
            }
        }
        rules.sort(Comparators.FLOW_RULE_COMPARATOR);

        if (suppressCoreOutput) {
            short coreAppId = coreService.getAppId("org.onosproject.core").id();
            rules = rules.stream()
                    .filter(f -> f.appId() != coreAppId)
                    .collect(Collectors.toList());
        }
        flows.put(d, rules);
    }
    return flows;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:46,代码来源:FlowsListCommand.java

示例11: replicasSortedByUtilization

import java.util.List; //导入方法依赖的package包/类
/**
 * Sort the partitions in the cluster by the utilization of the given resource.
 * @param resource the resource type.
 * @return a list of partitions sorted by utilization of the given resource.
 */
public List<Partition> replicasSortedByUtilization(Resource resource) {
  List<Partition> partitionList = new ArrayList<>();
  partitionList.addAll(_partitionsByTopicPartition.values());
  partitionList.sort((o1, o2) -> Double.compare(o2.leader().load().expectedUtilizationFor(resource),
                                                o1.leader().load().expectedUtilizationFor(resource)));
  return Collections.unmodifiableList(partitionList);
}
 
开发者ID:linkedin,项目名称:cruise-control,代码行数:13,代码来源:ClusterModel.java

示例12: orderBehaviours

import java.util.List; //导入方法依赖的package包/类
private List<Class<? extends Behaviour>> orderBehaviours(List<Driver> drivers) {
    // first, produce a set-union of all behaviours from all drivers...
    Set<Class<? extends Behaviour>> allBehaviours = new HashSet<>();
    drivers.forEach(d -> allBehaviours.addAll(d.behaviours()));

    // for now, order by alphanumeric name of the abstract behaviour simple name
    List<Class<? extends Behaviour>> ordered = new ArrayList<>(allBehaviours);
    ordered.sort(BEHAVIOUR_BY_NAME);
    return ordered;
}
 
开发者ID:shlee89,项目名称:athena,代码行数:11,代码来源:DriverViewMessageHandler.java

示例13: getId

import java.util.List; //导入方法依赖的package包/类
public static String getId(OfPatchLinkDto link) {
    List<String> attachedPorts = new ArrayList<>();
    attachedPorts.add(escape(getId(link.getPatchPort1())));
    attachedPorts.add(escape(getId(link.getPatchPort2())));
    attachedPorts.sort(Comparator.naturalOrder());
    return getId(attachedPorts, InventoryIdType.OFPLINK);
}
 
开发者ID:openNaEF,项目名称:openNaEF,代码行数:8,代码来源:InventoryIdCalculator.java

示例14: exec

import java.util.List; //导入方法依赖的package包/类
@Override
public DexMessage exec(Telemetry telemetry, ClassDesugarMessage message) {
    telemetry.message("Looking for Android SDK directory...");

    if (androidSdkPath != null) {
        telemetry.message("Android SDK modulePath: %s", androidSdkPath);
    } else {
        telemetry.error("Failed to get Android SDK modulePath");
        return new DexMessage(ExecutionStatus.ERROR, "Failed to get Android SDK modulePath");
    }

    File buildToolsDir = new File(androidSdkPath + "/build-tools");

    if (buildToolsDir.exists()) {
        File[] contents = buildToolsDir.listFiles();

        if (contents == null || contents.length == 0) {
            telemetry.error("Can't list build tools directories");
            return new DexMessage(ExecutionStatus.ERROR, "Can't list build tools directories");
        }

        List<File> dirList = new ArrayList<>();

        for (File file : contents) {
            if (file.isDirectory()) {
                dirList.add(file);
                telemetry.message("Found build tools directory: %s", file.getName());
            }
        }

        dirList.sort(Comparator.naturalOrder());

        if (dirList.isEmpty()) {
            telemetry.error("No build tools installed for Android SDK");
            return new DexMessage(ExecutionStatus.ERROR, "No build tools installed for Android SDK");
        }

        int size = dirList.size();
        String dxToolPath = dirList.get(size - 1).getAbsolutePath();
        telemetry.message("Using build tools %s for dx tool", dirList.get(size - 1).getName());

        if (!dexDir.exists() && !dexDir.mkdirs()) {
            telemetry.error("Failed to create modulePath: %s", dexDir.getAbsolutePath());
            return new DexMessage(ExecutionStatus.ERROR, "Failed to create DEX file directory");
        }

        telemetry.message("DEX files directory: %s", dexDir.getAbsolutePath());

        if (makeDex(telemetry, dxToolPath, lambdaDir.getAbsolutePath(), dexDir.getAbsolutePath())) {
            telemetry.message("DEX file(s) created");
            return new DexMessage();
        } else {
            telemetry.error("Failed to create DEX file(ss)");
            return new DexMessage(ExecutionStatus.ERROR, "Failed to create DEX file");
        }
    } else {
        telemetry.error("Directory /build-tools doesn't exist in Android SDK modulePath");
        return new DexMessage(ExecutionStatus.ERROR, "Directory /build-tools doesn't exist in Android SDK modulePath");
    }
}
 
开发者ID:andreyfomenkov,项目名称:green-cat,代码行数:61,代码来源:DexTask.java

示例15: buildStructures

import java.util.List; //导入方法依赖的package包/类
@Override
public List<TemplateStructure> buildStructures() {
    String resourceContext = config.getResourceContext();
    List<TemplateStructure> structures = synchronizedList(new ArrayList<>());
    List<TemplateStructure> descendents = synchronizedList(new ArrayList<>());
    xlinkmap.keySet().forEach(logical -> {
        Logical last = getLogicalLastDescendent(mets, logical);
        if (last != null) {
            List<Logical> logicalLastParentList =
                    getLogicalLastParent(mets, last.getLogicalId());
            logicalLastParentList.forEach(logicalLastParent -> {
                String lastParentId = logicalLastParent.getLogicalId();
                List<Logical> lastChildren =
                        getLogicalLastChildren(mets, lastParentId);
                //Map<String, String> logicalTypeMap = logDivs.stream().collect(
                //        toMap(Logical::getLogicalId, Logical::getLogicalType));

                List<String> ranges = synchronizedList(new ArrayList<>());
                lastChildren.forEach(desc -> {
                    TemplateStructure descSt = new TemplateStructure();
                    String descID = desc.getLogicalId().trim();
                    String rangeId = resourceContext + IIIF_RANGE + "/" + descID;
                    String descLabel = getLogicalLabel(mets, descID);
                    ranges.add(0, rangeId);
                    descSt.setStructureId(rangeId);
                    descSt.setStructureLabel(descLabel);
                    descSt.setStructureType(SC._Range);
                    descSt.setCanvases(getCanvases(descID));
                    descendents.add(0, descSt);
                });
                TemplateStructure st = new TemplateStructure();
                String structureIdDesc = resourceContext + IIIF_RANGE + "/" + lastParentId;
                st.setStructureId(structureIdDesc);
                String logicalLabel = getLogicalLabel(mets, lastParentId);
                st.setStructureLabel(logicalLabel);
                st.setStructureType(SC._Range);
                ranges.sort(naturalOrder());
                st.setRanges(ranges);
                st.setCanvases(getCanvases(lastParentId));
                if (!Objects.equals(
                        st.getStructureId(), resourceContext + IIIF_RANGE + "/" + "LOG_0000")) {
                    structures.add(0, st);
                }
            });

        }
    });
    Comparator<TemplateStructure> c = Comparator.comparing(TemplateStructure::getStructureId);
    List<TemplateStructure> results = Stream.concat(structures.stream(), descendents.stream())
            .filter(new ConcurrentSkipListSet<>(c)::add)
            .collect(Collectors.toList());
    results.sort(comparing(TemplateStructure::getStructureId));
    return results;
}
 
开发者ID:ubleipzig,项目名称:iiif-producer,代码行数:55,代码来源:MetsImpl.java


注:本文中的java.util.List.sort方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。