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

The following examples show how to use java.util.ArrayList#sort() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: dataenum   File: AccessSelector.java    License: Apache License 2.0 6 votes vote down vote up
private List<PackageAndAccess> parseAnnotatedPackages(
    Set<? extends Element> visibilityAnnotatedPackages) {
  ArrayList<PackageAndAccess> result = new ArrayList<>(visibilityAnnotatedPackages.size());

  for (Element element : visibilityAnnotatedPackages) {
    if (!(element instanceof PackageElement)) {
      throw new IllegalArgumentException(
          "received a access annotated element that is not a package: " + element);
    }

    PackageElement packageElement = (PackageElement) element;

    result.add(
        new PackageAndAccess(
            packageElement.getQualifiedName().toString(),
            element.getAnnotation(ConstructorAccess.class).value()));
  }

  result.sort((o1, o2) -> o2.packageName.length() - o1.packageName.length());

  return result;
}
 
Example 2
Source Project: netbeans   File: ConfigurationsNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected boolean createKeys(List<FileObject> keys) {
    ArrayList<FileObject> ret = new ArrayList<>(dep.getFiles().size());
    for (File file : dep.getFiles()) {
        FileObject fo = FileUtil.toFileObject(file);
        if (fo != null) {
            ret.add(fo);
        }
    }
    ret.sort(new Comparator<FileObject>() {
        @Override
        public int compare(FileObject o1, FileObject o2) {
            return o1.getNameExt().compareTo(o2.getNameExt());
        }
    });
    keys.addAll(ret);
    return true;
}
 
Example 3
public ArrayList<Integer> getPriorities() {
	MediaTypes[] mediaTypes = MediaTypes.values();

	ArrayList<Integer> priorities = new ArrayList<>(mediaTypes.length);
	for (MediaTypes type : mediaTypes) {
		priorities.add(type.getMediaCode());
	}

	Map<Integer, Mediatype> map = getMediatypes();
	priorities.sort((c1, c2) -> {
		Mediatype type1 = map.get(c1);
		Mediatype type2 = map.get(c2);

		if (type1 == null || type2 == null) {
			if (type1 == type2) {
				return 0;
			} else {
				return type1 == null ? 1 : -1;
			}
		} else {
			return type1.getPriority() - type2.getPriority();
		}
	});

	return priorities;
}
 
Example 4
@Test
public void testFindOrderBy() {
    for (StorableTest test : storableTests) {
        test.addAllToStorage();
        List<QueryParam> queryParams = Collections.emptyList();
        Collection<? extends Storable> allExisting = getStorageManager().list(test.getNameSpace());

        ArrayList<? extends Storable> sortedStorables = Lists.newArrayList(allExisting);
        sortedStorables.sort((Comparator<Storable>) (storable1, storable2) -> (int) (storable2.getId() - storable1.getId()));

        List<OrderByField> orderByFields = Lists.newArrayList(OrderByField.of("id", true));
        final Collection<Storable> allMatchingOrderByFilter = getStorageManager().find(test.getNameSpace(), queryParams, orderByFields);

        System.out.println("allMatchingOrderByFilter = " + allMatchingOrderByFilter);
        System.out.println("sortedStorables = " + sortedStorables);

        assertIterators(sortedStorables, allMatchingOrderByFilter);
    }
}
 
Example 5
Source Project: crate   File: Schemas.java    License: Apache License 2.0 6 votes vote down vote up
private static List<String> getSimilarTables(User user, String tableName, Iterable<TableInfo> tables) {
    LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
    ArrayList<Candidate> candidates = new ArrayList<>();
    for (TableInfo table : tables) {
        if (user.hasAnyPrivilege(Privilege.Clazz.TABLE, table.ident().fqn())) {
            String candidate = table.ident().name();
            float score = levenshteinDistance.getDistance(tableName.toLowerCase(Locale.ENGLISH), candidate.toLowerCase(Locale.ENGLISH));
            if (score > 0.7f) {
                candidates.add(new Candidate(score, candidate));
            }
        }
    }
    candidates.sort(Comparator.comparing((Candidate x) -> x.score).reversed());
    return candidates.stream()
        .limit(5)
        .map(x -> x.name)
        .collect(Collectors.toList());
}
 
Example 6
Source Project: impsort-maven-plugin   File: Grouper.java    License: Apache License 2.0 5 votes vote down vote up
static ArrayList<Group> parse(String groups) {
  ArrayList<Group> parsedGroups = new ArrayList<>();
  String[] array = requireNonNull(groups).replaceAll("\\s+", "").split(",");
  Pattern validGroup = Pattern.compile("^(?:\\w+(?:[.]\\w+)*[.]?|[*])$");
  // skip special case where the first element from split is empty and is the only element
  if (array.length != 1 || !array[0].isEmpty()) {
    for (String g : array) {
      if (!validGroup.matcher(g).matches()) {
        throw new IllegalArgumentException("Invalid group (" + g + ") in (" + groups + ")");
      }
      if (parsedGroups.stream().anyMatch(o -> g.contentEquals(o.getPrefix()))) {
        throw new IllegalArgumentException("Duplicate group (" + g + ") in (" + groups + ")");
      }

      int encounterOrder = parsedGroups.size();
      parsedGroups.add(new Group(g, encounterOrder));
    }
  }
  // include the default group if not already included
  if (parsedGroups.stream().noneMatch(o -> "*".contentEquals(o.getPrefix()))) {
    parsedGroups.add(new Group("*", parsedGroups.size()));
  }
  parsedGroups.sort((a, b) -> {
    // sort in reverse prefix length order first, then encounter order
    int comp = Integer.compare(b.getPrefix().length(), a.getPrefix().length());
    return comp != 0 ? comp : Integer.compare(a.getOrder(), a.getOrder());
  });
  return parsedGroups;
}
 
Example 7
Source Project: xibalba   File: MapHelpers.java    License: MIT License 5 votes vote down vote up
/**
 * Get all entities in vision of the player.
 *
 * @return List of entities within player's vision
 */
ArrayList<Entity> getEnemiesInPlayerVision() {
  ArrayList<Entity> enemies = new ArrayList<>();

  PositionComponent position = ComponentMappers.position.get(WorldManager.player);
  AttributesComponent attributes = ComponentMappers.attributes.get(WorldManager.player);

  int positionX = (int) position.pos.x;
  int positionY = (int) position.pos.y;

  for (int x = positionX - attributes.vision; x < positionX + attributes.vision; x++) {
    for (int y = positionY - attributes.vision; y < positionY + attributes.vision; y++) {
      Entity enemy = getEnemyAt(x, y);

      if (enemy != null) {
        enemies.add(enemy);
      }
    }
  }

  enemies.sort((enemy1, enemy2) -> {
    PositionComponent enemy1Position = ComponentMappers.position.get(enemy1);
    PositionComponent enemy2Position = ComponentMappers.position.get(enemy2);

    return enemy1Position.pos.x > enemy2Position.pos.x
        && enemy1Position.pos.y > enemy2Position.pos.y
        ? -1 : 1;
  });

  return enemies;
}
 
Example 8
Source Project: Wurst7   File: Navigator.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void getSearchResults(ArrayList<Feature> list, String query)
{
	// clear display list
	list.clear();
	
	// add search results
	for(Feature mod : navigatorList)
		if(mod.getName().toLowerCase().contains(query)
			|| mod.getSearchTags().toLowerCase().contains(query)
			|| mod.getDescription().toLowerCase().contains(query))
			list.add(mod);
		
	Comparator<String> c = (o1, o2) -> {
		int index1 = o1.toLowerCase().indexOf(query);
		int index2 = o2.toLowerCase().indexOf(query);
		
		if(index1 == index2)
			return 0;
		else if(index1 == -1)
			return 1;
		else if(index2 == -1)
			return -1;
		else
			return index1 - index2;
	};
	
	// sort search results
	list.sort(Comparator.comparing(Feature::getName, c)
		.thenComparing(Feature::getSearchTags, c)
		.thenComparing(Feature::getDescription, c));
}
 
Example 9
/**
 * This method sort the task instances in an increasing order based on the required ram
 * configuration values.
 */
private ArrayList<RequiredRam> getSortedRAMInstances(Set<String> taskNameSet) {
  ArrayList<RequiredRam> ramRequirements = new ArrayList<>();
  TreeSet<Vertex> orderedTaskSet = new TreeSet<>(new VertexComparator());
  orderedTaskSet.addAll(this.taskVertexSet);
  Map<String, Double> taskRamMap = taskAttributes.getTaskRamMap(this.taskVertexSet);
  for (String taskName : taskNameSet) {
    Resource resource = TaskScheduleUtils.getResourceRequirement(taskName, taskRamMap,
        this.defaultResourceValue, this.maxContainerResourceValue, this.paddingPercentage);
    ramRequirements.add(new RequiredRam(taskName, resource.getRam()));
  }
  ramRequirements.sort(Collections.reverseOrder());
  return ramRequirements;
}
 
Example 10
Source Project: fdb-record-layer   File: PlanHashable.java    License: Apache License 2.0 5 votes vote down vote up
static int stringHashUnordered(@Nonnull Iterable<String> strings) {
    final ArrayList<Integer> hashes = new ArrayList<>();
    for (String str : strings) {
        hashes.add(str != null ? str.hashCode() : 0);
    }
    hashes.sort(Comparator.naturalOrder());
    return combineHashes(hashes);
}
 
Example 11
public static List<NodeIndexRange> getLongRanges(Map<String, String> ranges) {
    ArrayList<NodeIndexRange> longRangeList = new ArrayList<>();
    for (Entry<String, String> entry : ranges.entrySet()) {
        String[] pair = entry.getKey().split("-");
        long longStart = NumberParseUtil.parseLong(pair[0].trim());
        long longEnd = NumberParseUtil.parseLong(pair[1].trim());
        int nodeId = Integer.parseInt(entry.getValue().trim());
        longRangeList.add(new NodeIndexRange(nodeId, longStart, longEnd));
    }
    longRangeList.sort(Comparator.comparing(x -> x.valueStart));
    return longRangeList;
}
 
Example 12
public ArrayList<Alliance> getAllSortedAlliances() {
    ArrayList<Alliance> returnList = getAllAlliances();
    Comparator<Alliance> comparator = new Comparator<Alliance>() {
        @Override
        public int compare(Alliance o1, Alliance o2) {
            int o1Size = o1.getMembers().size();
            int o2Size = o2.getMembers().size();
            return Integer.compare(o1Size, o2Size);
        }
    };
    returnList.sort(comparator);
    return returnList;
}
 
Example 13
Source Project: onos   File: NextDstCommand.java    License: Apache License 2.0 5 votes vote down vote up
private void printDestinationSet(Map<DestinationSetNextObjectiveStoreKey,
                                  NextNeighbors> ds) {
    ArrayList<DestinationSetNextObjectiveStoreKey> a = new ArrayList<>();
    ds.keySet().forEach(key -> a.add(key));
    a.sort(new Comp());

    StringBuilder dsbldr = new StringBuilder();
    for (int i = 0; i < a.size(); i++) {
        dsbldr.append("\n " + a.get(i));
        dsbldr.append(" --> via: " + ds.get(a.get(i)));
    }
    print(FORMAT_MAPPING, dsbldr.toString());
}
 
Example 14
Source Project: PackageTemplates   File: StateEditor.java    License: Apache License 2.0 5 votes vote down vote up
public StateEditor reorderFavourites() {
    ArrayList<Favourite> listFavourite = model.getListFavourite();
    listFavourite.sort(Comparator.comparingInt(Favourite::getOrder));

    for (int i = 0; i < listFavourite.size(); i++) {
        listFavourite.get(i).setOrder(i);
    }
    return this;
}
 
Example 15
public static List<TradeCurrency> getAllOKPayCurrencies() {
    ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList(
            new FiatCurrency("EUR"),
            new FiatCurrency("USD"),
            new FiatCurrency("GBP"),
            new FiatCurrency("CHF"),
            new FiatCurrency("RUB"),
            new FiatCurrency("PLN"),
            new FiatCurrency("JPY"),
            new FiatCurrency("CAD"),
            new FiatCurrency("AUD"),
            new FiatCurrency("CZK"),
            new FiatCurrency("NOK"),
            new FiatCurrency("SEK"),
            new FiatCurrency("DKK"),
            new FiatCurrency("HRK"),
            new FiatCurrency("HUF"),
            new FiatCurrency("NZD"),
            new FiatCurrency("RON"),
            new FiatCurrency("TRY"),
            new FiatCurrency("ZAR"),
            new FiatCurrency("HKD"),
            new FiatCurrency("CNY")
    ));
    currencies.sort(Comparator.comparing(TradeCurrency::getCode));
    return currencies;
}
 
Example 16
Source Project: Box   File: TypeSearch.java    License: Apache License 2.0 4 votes vote down vote up
private void fillTypeCandidates(SSAVar ssaVar) {
	TypeSearchVarInfo varInfo = state.getVarInfo(ssaVar);
	ArgType immutableType = ssaVar.getImmutableType();
	if (immutableType != null) {
		varInfo.markResolved(immutableType);
		return;
	}
	ArgType currentType = ssaVar.getTypeInfo().getType();
	if (currentType.isTypeKnown()) {
		varInfo.markResolved(currentType);
		return;
	}

	Set<ArgType> assigns = new LinkedHashSet<>();
	Set<ArgType> uses = new LinkedHashSet<>();
	Set<ITypeBound> bounds = ssaVar.getTypeInfo().getBounds();
	for (ITypeBound bound : bounds) {
		if (bound.getBound() == BoundEnum.ASSIGN) {
			assigns.add(bound.getType());
		} else {
			uses.add(bound.getType());
		}
	}

	Set<ArgType> candidateTypes = new LinkedHashSet<>();
	addCandidateTypes(bounds, candidateTypes, assigns);
	addCandidateTypes(bounds, candidateTypes, uses);

	for (ArgType assignType : assigns) {
		addCandidateTypes(bounds, candidateTypes, getWiderTypes(assignType));
	}
	for (ArgType useType : uses) {
		addCandidateTypes(bounds, candidateTypes, getNarrowTypes(useType));
	}

	addUsageTypeCandidates(ssaVar, bounds, candidateTypes);

	int size = candidateTypes.size();
	if (size == 0) {
		varInfo.setTypeResolved(true);
		varInfo.setCurrentType(ArgType.UNKNOWN);
		varInfo.setCandidateTypes(Collections.emptyList());
	} else if (size == 1) {
		varInfo.setTypeResolved(true);
		varInfo.setCurrentType(candidateTypes.iterator().next());
		varInfo.setCandidateTypes(Collections.emptyList());
	} else {
		varInfo.setTypeResolved(false);
		varInfo.setCurrentType(ArgType.UNKNOWN);
		ArrayList<ArgType> types = new ArrayList<>(candidateTypes);
		types.sort(typeCompare.getReversedComparator());
		varInfo.setCandidateTypes(Collections.unmodifiableList(types));
	}
}
 
Example 17
Source Project: presto   File: TestAsyncQueue.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testBorrow()
        throws Exception
{
    // The numbers are chosen so that depletion of elements can happen.
    // Size is 5. Two threads each borrowing 3 can deplete the queue.
    // The third thread may try to borrow when the queue is already empty.
    // We also want to confirm that isFinished won't return true even if queue is depleted.

    AsyncQueue<Integer> queue = new AsyncQueue<>(4, executor);
    queue.offer(1);
    queue.offer(2);
    queue.offer(3);
    queue.offer(4);
    queue.offer(5);

    // Repeatedly remove up to 3 elements and re-insert them.
    Runnable runnable = () -> {
        for (int i = 0; i < 700; i++) {
            getFutureValue(queue.borrowBatchAsync(3, elements -> new BorrowResult<>(elements, null)));
        }
    };

    Future<?> future1 = executor.submit(runnable);
    Future<?> future2 = executor.submit(runnable);
    Future<?> future3 = executor.submit(runnable);
    future1.get();
    future2.get();
    future3.get();

    queue.finish();
    assertFalse(queue.isFinished());

    AtomicBoolean done = new AtomicBoolean();
    executor.submit(() -> {
        while (!done.get()) {
            assertFalse(queue.isFinished() || done.get());
        }
    });

    future1 = executor.submit(runnable);
    future2 = executor.submit(runnable);
    future3 = executor.submit(runnable);
    future1.get();
    future2.get();
    future3.get();
    done.set(true);

    assertFalse(queue.isFinished());
    ArrayList<Integer> list = new ArrayList<>(queue.getBatchAsync(100).get());
    list.sort(Integer::compare);
    assertEquals(list, ImmutableList.of(1, 2, 3, 4, 5));
    assertTrue(queue.isFinished());
}
 
Example 18
Source Project: onos   File: KShortestPathsSearch.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected Result<V, E> internalSearch(Graph<V, E> graph, V src, V dst, EdgeWeigher<V, E> weigher, int maxPaths) {
    //The modified edge weigher removes any need to modify the original graph
    InnerEdgeWeigher modifiedWeighter = new InnerEdgeWeigher(checkNotNull(weigher));
    checkArgument(maxPaths != ALL_PATHS, "KShortestPath search cannot" +
            "be used with ALL_PATHS.");
    checkArgument(maxPaths > 0, "The max number of paths must be greater" +
            " than 0");
    Graph<V, E> originalGraph = checkNotNull(graph);
    //the result contains the set of eventual results
    InnerOrderedResult result = new InnerOrderedResult(src, dst, maxPaths);
    ArrayList<Path<V, E>> resultPaths = new ArrayList<>(maxPaths);
    ArrayList<Path<V, E>> potentialPaths = Lists.newArrayList();

    DijkstraGraphSearch<V, E> dijkstraSearch = new DijkstraGraphSearch<>();
    Set<Path<V, E>> dijkstraResults = dijkstraSearch.search(originalGraph, src, dst, modifiedWeighter, 1).paths();
    //Checks if the dst was reachable
    if (dijkstraResults.isEmpty()) {
        log.warn("No path was found.");
        return result;
    }
    //If it was reachable adds the first shortest path to the set of results
    resultPaths.add(dijkstraResults.iterator().next());

    for (int k = 1; k < maxPaths; k++) {

        for (int i = 0; i < resultPaths.get(k - 1).edges().size(); i++) {
            V spurNode = resultPaths.get(k - 1).edges().get(i).src();
            List<E> rootPathEdgeList = resultPaths.get(k - 1).edges().subList(0, i);

            for (Path<V, E> path : resultPaths) {
                if (path.edges().size() >= i && edgeListsAreEqual(rootPathEdgeList, path.edges().subList(0, i))) {
                    modifiedWeighter.removedEdges.add(path.edges().get(i));
                }
            }

            //Effectively remove all nodes from the source path
            for (E edge : rootPathEdgeList) {
                originalGraph.getEdgesFrom(edge.src()).forEach(e -> modifiedWeighter.removedEdges.add(e));
                originalGraph.getEdgesTo(edge.src()).forEach(e -> modifiedWeighter.removedEdges.add(e));
            }

            dijkstraResults = dijkstraSearch.search(originalGraph, spurNode, dst, modifiedWeighter, 1).paths();
            if (!dijkstraResults.isEmpty()) {
                Path<V, E> spurPath = dijkstraResults.iterator().next();
                List<E> totalPath = new ArrayList<>(rootPathEdgeList);
                spurPath.edges().forEach(totalPath::add);
                //The following line must use the original weigher not the modified weigher because the modified
                //weigher will count -1 values used for modifying the graph and return an inaccurate cost.
                potentialPaths.add(new DefaultPath<>(totalPath,
                        calculatePathCost(weigher, totalPath)));
            }

            //Restore all removed paths and nodes
            modifiedWeighter.removedEdges.clear();
        }
        if (potentialPaths.isEmpty()) {
            break;
        }
        potentialPaths.sort(new InnerPathComparator());
        resultPaths.add(potentialPaths.get(0));
        potentialPaths.remove(0);
    }
    result.pathSet.addAll(resultPaths);

    return result;
}
 
Example 19
@Override
public void render(float partialTicks, int destroyStage, float alpha) {
	ArrayList<BlockPos> errors = new ArrayList<>(((IStructure) tile.getBlockType()).testStructure(tile.getWorld(), tile.getPos()));
	errors.sort(Vec3i::compareTo);

	ItemStack input = tile.getInput();
	if (input.isEmpty()) {
		input = tile.getOutput();
		if (input.isEmpty()) {
			input = ItemStack.EMPTY;
		}
	}

	ICraftingPlateRecipe recipeForItem = CraftingPlateRecipeManager.getRecipe(tile.getWorld(), tile.getPos(), input);
	if (recipeForItem != null) recipeForItem.renderInput(tile.getWorld(), tile.getPos(), input, partialTicks);

	if (!errors.isEmpty() && tile.revealStructure && tile.getBlockType() instanceof IStructure) {
		ModStructures.structureManager.draw(ModStructures.CRAFTING_PLATE, (float) (Math.sin(ClientTickHandler.getTicks() / 10.0) + 1) / 10.0f + 0.3f);
	}

	if (!errors.isEmpty()) {
		for (BlockPos error : errors) {
			StructureErrorRenderer.addError(error);
		}
		return;
	} else if (tile.getWorld().isAirBlock(tile.getPos().offset(EnumFacing.UP)) && !CraftingPlateRecipeManager.doesRecipeExist(tile.getWorld(), tile.getPos(), input) && RandUtil.nextInt(4) == 0) {
		LibParticles.CRAFTING_ALTAR_IDLE(tile.getWorld(), new Vec3d(tile.getPos()).add(0.5, 0.7, 0.5));
	}

	// render each item at its current position
	final int mapSize = hoveringStacks.size();
	for (HoveringStack hoveringStack : hoveringStacks.values()) {

		if (!hoveringStack.stack.isEmpty()) {

			{
				GlStateManager.pushMatrix();
				GlStateManager.translate(0.5 + hoveringStack.location.x, 1 + hoveringStack.location.y, 0.5 + hoveringStack.location.z);
				GlStateManager.scale(0.3, 0.3, 0.3);
				GlStateManager.rotate((hoveringStack.randX + ClientTickHandler.getTicks()), 0, 1, 0);
				GlStateManager.rotate((hoveringStack.randY + ClientTickHandler.getTicks()), 1, 0, 0);
				GlStateManager.rotate((hoveringStack.randZ + ClientTickHandler.getTicks()), 0, 0, 1);

				GlStateManager.enableLighting();
				RenderHelper.disableStandardItemLighting();
				Minecraft.getMinecraft().getRenderItem().renderItem(hoveringStack.stack, TransformType.NONE);
				RenderHelper.enableStandardItemLighting();
				GlStateManager.popMatrix();
			}

			if (tile.suckingCooldown <= 0) {
				if (RandUtil.nextInt(mapSize / 2) == 0) {
					LibParticles.CLUSTER_DRAPE(
							tile.getWorld(),
							hoveringStack.location.add(new Vec3d(tile.getPos())).add(0.5, 0.5, 0.5));
				}
			} else {
				if (RandUtil.nextInt(mapSize) == 0) {
					LibParticles.CRAFTING_ALTAR_CLUSTER_SUCTION(
							tile.getWorld(),
							new Vec3d(tile.getPos()).add(0.5, 0.75, 0.5),
							new InterpBezier3D(hoveringStack.location, new Vec3d(0, 0, 0)));
				}
			}
		}
	}
}
 
Example 20
private void runTest(MockInputPlanNode input) {
	Unique unique = new Unique(input);

	List<Tuple> tuples = new MockConsumePlanNode(unique).asList();

	ArrayList<Tuple> expected = new ArrayList<>(new HashSet<>(new MockConsumePlanNode(input).asList()));

	tuples.sort(Tuple::compareTo);
	expected.sort(Tuple::compareTo);

	assertEquals(expected, tuples);
}