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

The following are Jave code examples for showing how to use sort() of the java.util.List class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: elasticsearch_my   File: SuggestTests.java   View Source Code Vote up 6 votes
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()));
    }
}
 
Example 2
Project: shoucang   File: PostListService.java   View Source Code Vote up 6 votes
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;
}
 
Example 3
Project: pzubaha   File: UserSort.java   View Source Code Vote up 6 votes
/**
 * 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;
}
 
Example 4
Project: MeeCreeps   File: AngryActionWorker.java   View Source Code Vote up 6 votes
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;
}
 
Example 5
Project: Pet-Supply-Store   File: TestEntityEndpoint.java   View Source Code Vote up 6 votes
/**
 * {@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;
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: DefaultAccessLogPatternParser.java   View Source Code Vote up 6 votes
/**
 * 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);
}
 
Example 7
Project: BaseClient   File: HUD.java   View Source Code Vote up 6 votes
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;
}
 
Example 8
Project: MeeCreeps   File: FlattenAreaActionWorker.java   View Source Code Vote up 5 votes
/**
 * 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);
}
 
Example 9
Project: litiengine   File: PhysicsEngine.java   View Source Code Vote up 5 votes
@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;
}
 
Example 10
Project: athena   File: FlowsListCommand.java   View Source Code Vote up 5 votes
/**
 * 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;
}
 
Example 11
Project: cruise-control   File: ClusterModel.java   View Source Code Vote up 5 votes
/**
 * 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);
}
 
Example 12
Project: athena   File: DriverViewMessageHandler.java   View Source Code Vote up 5 votes
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;
}
 
Example 13
Project: openNaEF   File: InventoryIdCalculator.java   View Source Code Vote up 5 votes
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);
}
 
Example 14
Project: green-cat   File: DexTask.java   View Source Code Vote up 4 votes
@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");
    }
}
 
Example 15
Project: iiif-producer   File: MetsImpl.java   View Source Code Vote up 4 votes
@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;
}
 
Example 16
Project: pnc-repressurized   File: TileEntitySentryTurret.java   View Source Code Vote up 4 votes
@Override
public void update() {
    super.update();
    if (!getWorld().isRemote) {
        range = 16 + Math.min(16, getUpgrades(EnumUpgrade.RANGE));
        if (getMinigun().getAttackTarget() == null && redstoneAllows()) {
            getMinigun().setSweeping(true);
            if (getWorld().getTotalWorldTime() % 20 == 0) {
                List<EntityLivingBase> entities = getWorld().getEntitiesWithinAABB(EntityLivingBase.class, getTargetingBoundingBox(), entitySelector);
                if (entities.size() > 0) {
                    entities.sort(new TargetSorter());
                    getMinigun().setAttackTarget(entities.get(0));
                    targetEntityId = entities.get(0).getEntityId();
                }
            }
        } else {
            getMinigun().setSweeping(false);
        }
        EntityLivingBase target = getMinigun().getAttackTarget();
        if (target != null) {
            if (!redstoneAllows() || !entitySelector.apply(target)) {
                getMinigun().setAttackTarget(null);
                targetEntityId = -1;
            } else {
                if (getWorld().getTotalWorldTime() % 5 == 0) {
                    getFakePlayer().setPosition(getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5); //Make sure the knockback has the right direction.
                    boolean usedAmmo = getMinigun().tryFireMinigun(target);
                    if (usedAmmo) {
                        for (int i = 0; i < inventory.getSlots(); i++) {
                            if (!inventory.getStackInSlot(i).isEmpty()) {
                                inventory.setStackInSlot(i, ItemStack.EMPTY);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    getMinigun().update(getPos().getX() + 0.5, getPos().getY() + 0.5, getPos().getZ() + 0.5);
}
 
Example 17
Project: stewie   File: Service.java   View Source Code Vote up 4 votes
@Override
public Iterator<EndPointInfo> iterator()
{
    final List<EndPointInfo> endPoints = new ArrayList<>();

    File[] roots = root.listFiles();

    if (roots != null)
    {
        for (File current : roots)
        {
            String name = current.getName().substring(0, current.getName().length() - 5);

            if (!name.endsWith("Module"))
            {
                EndPointInfo endPointInfo = new EndPointInfo(toString(), current);
                endPoints.add(endPointInfo);
            }
        }
    }

    endPoints.sort(Comparator.comparing(EndPointInfo::name));

    return new Iterator<EndPointInfo>()
    {
        private int index = 0;

        @Override
        public boolean hasNext()
        {
            return index < endPoints.size();
        }

        @Override
        public EndPointInfo next()
        {
            if (index < endPoints.size())
            {
                return endPoints.get(index++);
            }
            else
            {
                throw new NoSuchElementException();
            }
        }
    };
}
 
Example 18
Project: WanderingHorde   File: Horde.java   View Source Code Vote up 4 votes
/**
 * Called by the anchor creature when it dies or is destroyed, then picks
 * a new anchor from the satellites. Horde is considered destroyed when no
 * more creatures exist.
 */
public boolean newAnchor() {
    if (satellites.isEmpty()) {
        WanderingHorde.logger.warning(String.format("Can't pick new anchor because there are no satellites left in %s.", this));
        return false;
    }

    List<Member> list = new ArrayList<>(satellites);
    list.sort((left, right) -> Float.compare(left.distanceTo(anchorman), right.distanceTo(anchorman)));
    
    // waypoint reference was the anchorman?
    boolean anchormanRef = waypoints.referenceCreature != null && waypoints.referenceCreature.equals(anchorman);

    WanderingHorde.switchAnchorman(anchorman, list.get(0));
    anchorman = list.get(0);
    satellites.remove(anchorman);
    
    // set new waypoint reference creature to new anchorman.
    if (anchormanRef) waypoints.referenceCreature = anchorman;
    
    list.clear();
    list = null;
    
    WanderingHorde.logger.info(String.format("New anchor. Closest satellite %s is new anchor for %s.", anchorman, this));

    /**
     * Finding the closest tile in the path to the new anchorman.
     */
    HordePath path = waypoints.path();
    LinkedList<PathTile> tiles = path.get().getPathTiles();
    int minDist = Integer.MAX_VALUE;
    
    for (int i = tiles.size() - 1; i >= 0; i--) {
        PathTile tile = tiles.get(i);
        
        int distance = Math.max(Math.abs(anchorman.getTileX() - tile.getTileX()), Math.abs(anchorman.getTileY() - tile.getTileY()));
        
        if (distance > minDist) {
            path.index = i;
            break;
        }
        
        minDist = distance;
    }
    
    WanderingHorde.logger.info(String.format("Found that %s is dist=%d closest to %s.", path.current(), minDist, anchorman));
    
    return true;
}
 
Example 19
Project: Robot-Vision-API   File: TargetDetector.java   View Source Code Vote up 4 votes
/**
 * Detect the target in the image.
 *
 * @param frame The image to detect targetDetection in.
 * @return The list of possible targetDetection ordered by confidence from greatest to least.
 */
@Override
public List<Target> detect(Mat frame) {
    Mat filtered = filter.filter(frame);

    ContourFinder contourFinder = new StandardContourFinder();

    List<MatOfPoint> contours = contourFinder.findContours(filtered);

    filtered.release();

    contours = contourFilter.filterContours(contours);


    List<Target> detections = new ArrayList<>();
    for (MatOfPoint contour : contours) {
        Rect boundary = Imgproc.boundingRect(contour);
        double aspectRatio = (boundary.width / (double) boundary.height);
        double aspectScore = Scorer.score(aspectRatio, targetSpecs.getWidth() / targetSpecs.getHeight());

        double areaRatio = Imgproc.contourArea(contour) / (double) boundary.area();
        double areaScore = Scorer.score(areaRatio,
                targetSpecs.getArea() / (targetSpecs.getHeight() * targetSpecs.getWidth()));

        double confidence = Math.round((aspectScore + areaScore) / 2) / 100.0;

        Moments moments = Imgproc.moments(contour);

        Point centerOfMass = new Point(moments.m10 / moments.m00, moments.m01 / moments.m00, 0);

        Target target = new Target(confidence, boundary.width - 1, boundary.height - 1,
                new Point(boundary.x, boundary.y, 0), centerOfMass, frame.size());
        detections.add(target);
    }
    detections.sort((a, b) -> {
        if (b.getIsTargetProbability() > a.getIsTargetProbability()) {
            return 1;
        } else if (a.getIsTargetProbability() > b.getIsTargetProbability()) {
            return -1;
        }
        return 0;
    });
    return detections;
}
 
Example 20
Project: AptSpring   File: SpringAnnotationParser.java   View Source Code Vote up 4 votes
private List<Modifier> getIllegalModifiers(Set<Modifier> existing, List<Modifier> illegal) {
  List<Modifier> modifiers = new ArrayList<>(existing);
  modifiers.removeIf(modifier -> !illegal.contains(modifier));
  modifiers.sort((m1, m2) ->  m1.name().compareTo(m2.name())); //in case someone reorders
  return modifiers;
}