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

The following are Jave code examples for showing how to use sort() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Text-Rabbit   File: Highscores_Standard.java   Source Code and License Vote up 6 votes
@Override
protected void onCreate(Bundle savedInstanceState)
{
    setTitle(Game.TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_highscores__standard);

    ArrayList<String> userNames = Game.readFile(Highscores_Standard.this,Game.USERSFILENAME);
    ArrayList<String> userScores = Game.readFile(Highscores_Standard.this,Game.SCORESFILENAME);

    ArrayList<User> users = new ArrayList<User>();

    for (int x = 0; x < userNames.size(); x++)
    {
        users.add(new User(userNames.get(x),Float.parseFloat(userScores.get(x))));
    }

    users.sort(Comparator.comparing(User::getScore));
    Collections.reverse(users);

    ListView listView = (ListView) findViewById(R.id.listBox);
    ArrayAdapter<User> arrayAdapter = new ArrayAdapter<User>(this,android.R.layout.simple_list_item_1,users);
    listView.setAdapter(arrayAdapter);

}
 
Example 2
Project: Text-Rabbit   File: Highscores_Classic.java   Source Code and License Vote up 6 votes
@Override
protected void onCreate(Bundle savedInstanceState)
{
    setTitle(Game.TITLE);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_highscores__classic);

    ArrayList<String> userNames = Game.readFile(Highscores_Classic.this,Game.C_USERSFILENAME);
    ArrayList<String> userScores = Game.readFile(Highscores_Classic.this,Game.C_SCORESFILENAME);

    ArrayList<User> users = new ArrayList<User>();

    for (int x = 0; x < userNames.size(); x++)
    {
        users.add(new User(userNames.get(x),Float.parseFloat(userScores.get(x))));
    }

    users.sort(Comparator.comparing(User::getScore));
    Collections.reverse(users);

    ListView listView = (ListView) findViewById(R.id.listBox);
    ArrayAdapter<User> arrayAdapter = new ArrayAdapter<User>(this,android.R.layout.simple_list_item_1,users);
    listView.setAdapter(arrayAdapter);
}
 
Example 3
Project: ULCRS   File: DataParse.java   Source Code and License Vote up 6 votes
/**
 * Parse shifts, then courses, then tutors, in that order, from Json received from ULC.
 * Courses depend on shifts, and tutors depend on shifts and courses (which depend on shifts), so to reduce
 * redundant parsing, this "shift -> course -> tutor" order should be enforced.
 *
 * @param input - JsonObject response from ULC to parse into ULCRS data.
 * @return ParsedULCResponse - parsed response Json received from ULC.
 */
public static ParsedULCResponse parse(JsonObject input) {
    ParsedULCResponse parsed = new ParsedULCResponse();

    // Shifts
    HashMap<Integer, Shift> shifts = parseShifts(input);
    ArrayList<Shift> shiftsList = new ArrayList<>(shifts.values());
    shiftsList.sort(Comparator.comparingInt(Shift::getId));
    parsed.setShifts(shiftsList);

    // Courses
    HashMap<Integer, Course> courses = parseCourses(input, shifts);
    ArrayList<Course> coursesList = new ArrayList<>(courses.values());
    coursesList.sort(Comparator.comparingInt(Course::getId));
    parsed.setCourses(coursesList);

    // Tutors
    HashMap<Integer, Tutor> tutors = parseTutors(input, shifts, courses);
    ArrayList<Tutor> tutorsList = new ArrayList<>(tutors.values());
    tutorsList.sort(Comparator.comparingInt(Tutor::getId));
    parsed.setTutors(new ArrayList<>(tutorsList));

    return filter(parsed);
}
 
Example 4
Project: anki-cards-web-browser   File: DeckWithCategories.java   Source Code and License Vote up 6 votes
@Override
protected void addCardsToJson(JSONObject json, boolean randomizeCardsPositions) {
    JSONArray categoriesArray = new JSONArray();

    ArrayList<String> tags = new ArrayList<>(tagsCards.keySet());
    tags.sort(NaturalOrderComparator.INSTANCE);

    tags.forEach(tag -> {
        ArrayList<RenderedCard> cards = tagsCards.get(tag);
        if (randomizeCardsPositions) {
            Collections.shuffle(cards);
        }

        JSONArray cardsOfCategory = new JSONArray();
        cards.forEach(card -> cardsOfCategory.put(calculateCardJSON(card)));

        JSONObject categoryObject = new JSONObject();
        categoryObject.put("categoryName", tag.trim());
        categoryObject.put("cards", cardsOfCategory);

        categoriesArray.put(categoryObject);
    });

    json.put("categories", categoriesArray);
}
 
Example 5
Project: StructPro   File: Structures.java   Source Code and License Vote up 5 votes
/**
 * Sort village structures by size
 * Firstly goes structures with smallest clearance
 */
private static void sortVillages() {
    for (ArrayList<Structure> village : villages.select()) {
        village.sort((lhs, rhs) -> {
            int lSize = Math.max(lhs.getWidth(), lhs.getLength());
            int rSize = Math.max(rhs.getWidth(), rhs.getLength());
            if (lSize == rSize) return 0;
            return rSize > lSize ? 1 : -1;
        });
    }
}
 
Example 6
Project: r8   File: JarState.java   Source Code and License Vote up 5 votes
public List<Local> openLocals(LabelNode label) {
  Collection<LocalVariableNode> nodes = localVariableStartPoints.get(label);
  ArrayList<Local> locals = new ArrayList<>(nodes.size());
  for (LocalVariableNode node : nodes) {
    locals.add(setLocalInfo(node.index, Type.getType(node.desc), localVariables.get(node)));
  }
  // Sort to ensure deterministic instruction ordering (correctness is unaffected).
  locals.sort(Comparator.comparingInt(local -> local.slot.register));
  return locals;
}
 
Example 7
Project: twitter-anomalyDetection-java   File: DetectAnoms.java   Source Code and License Vote up 5 votes
private int[] getOrder(double[] data) {
    if (data == null || data.length < 1)
        return null;
    int len = data.length;
    ArrayList<Pair> map = new ArrayList<Pair>();
    for (int i = 0; i < len; ++i) {
        map.add(new Pair(i, data[i]));
    }
    map.sort(new PairValueComparator());
    int[] returnOrder = new int[len];
    for (int i = 0; i < len; ++i) {
        returnOrder[i] = map.get(i).key;
    }
    return returnOrder;
}
 
Example 8
Project: hack-man-2-engine   File: AbstractEnemyAI.java   Source Code and License Vote up 5 votes
/**
 * Returns the player states sorted from closest to farthest to enemy
 */
ArrayList<HackMan2PlayerState> getSortedPlayers(Point coordinate, HackMan2State state) {
    ArrayList<HackMan2PlayerState> playerStates = new ArrayList<>(state.getPlayerStates());

    // Shuffle to get random player state on same distance values
    Collections.shuffle(playerStates, HackMan2Engine.RANDOM);

    // Sort from closest to farthest away from enemy coordinate
    playerStates.sort(
            Comparator.comparingDouble(ps -> coordinate.distance(ps.getCoordinate())));

    return playerStates;
}
 
Example 9
Project: annoflex   File: ImportInserter.java   Source Code and License Vote up 5 votes
/**
 * 
 */
private ArrayList<ImportEntry> createSortedImportList(HashSet<TypeDescriptor> newImports) {
    ArrayList<ImportEntry> sortedImports = new ArrayList<>();
    Iterator<TypeDescriptor> iterator = newImports.iterator();
    
    while (iterator.hasNext()) {
        sortedImports.add(new ImportEntry(iterator.next(),null));
    }
    
    sortedImports.sort(null);
    
    return sortedImports;
}
 
Example 10
Project: xcc   File: SubtargetEmitter.java   Source Code and License Vote up 5 votes
/**
 * generate cpu name to itinerary lookup table.
 * @param os
 */
private void emitProcessorLookup(PrintStream os) throws Exception
{
    ArrayList<Record> processorList = records.getAllDerivedDefinition("Processor");

    processorList.sort(LessRecord);

    os.println();
    os.printf("// Sorted (by key) array of itineraries for CPU subtype.\n" +
            "public static final SubtargetInfoKV[] procItinKV = {\n");

    // For each processor
    for (int i = 0, n = processorList.size(); i != n; i++)
    {
        Record processor = processorList.get(i);

        String name = processor.getValueAsString("Name");
        String procItin = processor.getValueAsDef("ProcItin").getName();

        // Emit as { "cpu", procinit },
        os.printf("\tnew SubtargetInfoKV(\"%s\", %s)",
                name, procItin);

        // Depending on ''if more in the list'' emit comma
        if (i < n - 1) os.print(",");
        os.println();
    }
    os.println("};");
}
 
Example 11
Project: EmoticonGIFKeyboard   File: Main.java   Source Code and License Vote up 5 votes
/**
 * Create the regex to find emoticons and save it to the shared preference. This will generate
 * regex by adding unicode of all emoticons separated by '|'.
 *
 * @param unicodesForPattern List of all the supported unicodes from the database.
 */
private static void createAndSaveEmoticonRegex(final ArrayList<String> unicodesForPattern) {
    // We need to sort the unicodes by length so the longest one gets matched first.
    unicodesForPattern.sort(STRING_LENGTH_COMPARATOR);

    StringBuilder unicodeRegex = new StringBuilder();
    for (String unicode : unicodesForPattern)
        unicodeRegex.append(Pattern.quote(unicode)).append("|");
    if (unicodeRegex.toString().endsWith("|"))
        unicodeRegex = new StringBuilder(unicodeRegex.substring(0, unicodeRegex.length() - 1));

    //Save the regex
    Utils.saveFile(new File(Utils.CURRENT_DIR_PATH + "/regex"), unicodeRegex.toString());
}
 
Example 12
Project: cyberduck   File: CryptoBulkFeature.java   Source Code and License Vote up 4 votes
@Override
public R pre(final Transfer.Type type, final Map<Path, TransferStatus> files, final ConnectionCallback callback) throws BackgroundException {
    final Map<Path, TransferStatus> encrypted = new HashMap<>(files.size());
    final ArrayList<Map.Entry<Path, TransferStatus>> sorted = new ArrayList<>(files.entrySet());
    // Sort with folder first in list
    sorted.sort(new Comparator<Map.Entry<Path, TransferStatus>>() {
        @Override
        public int compare(final Map.Entry<Path, TransferStatus> o1, final Map.Entry<Path, TransferStatus> o2) {
            return new PathPriorityComparator().compare(o1.getKey(), o2.getKey());
        }
    });
    for(Map.Entry<Path, TransferStatus> entry : sorted) {
        final Path file = entry.getKey();
        final TransferStatus status = entry.getValue();
        if(null == status.getHeader()) {
            // Write header to be reused in writer
            final Cryptor cryptor = cryptomator.getCryptor();
            final FileHeader header = cryptor.fileHeaderCryptor().create();
            status.setHeader(cryptor.fileHeaderCryptor().encryptHeader(header));
        }
        if(null == status.getNonces()) {
            status.setNonces(new RandomNonceGenerator());
        }
        if(file.isDirectory()) {
            if(!status.isExists()) {
                switch(type) {
                    case upload:
                        // Preset directory ID for new folders to avert lookup with not found failure in directory ID provider
                        final String directoryId = random.random();
                        encrypted.put(cryptomator.encrypt(session, file, directoryId, false), status);
                        break;
                    default:
                        encrypted.put(cryptomator.encrypt(session, file), status);
                        break;
                }
            }
            else {
                encrypted.put(cryptomator.encrypt(session, file), status);
            }
        }
        else {
            encrypted.put(cryptomator.encrypt(session, file), status);
        }
    }
    return delegate.pre(type, encrypted, callback);
}
 
Example 13
Project: H-Uppaal   File: ProjectPaneController.java   Source Code and License Vote up 4 votes
private void sortPresentations() {
    final ArrayList<Component> sortedComponentList = new ArrayList<>();
    componentPresentationMap.keySet().forEach(sortedComponentList::add);
    sortedComponentList.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
    sortedComponentList.forEach(component -> componentPresentationMap.get(component).toFront());
}
 
Example 14
Project: dxram   File: OverlayPeer.java   Source Code and License Vote up 4 votes
/**
 * Get the status of the superpeer storage.
 *
 * @return Status of the superpeer storage.
 */
public SuperpeerStorage.Status superpeerStorageGetStatus() {
    SuperpeerStorage.Status[] statusArray = new SuperpeerStorage.Status[m_superpeers.size()];

    m_overlayLock.readLock().lock();
    for (int i = 0; i < m_superpeers.size(); i++) {
        short superpeer = m_superpeers.get(i);
        m_overlayLock.readLock().unlock();

        SuperpeerStorageStatusRequest request = new SuperpeerStorageStatusRequest(superpeer);
        try {
            m_network.sendSync(request);
            statusArray[i] = request.getResponse(SuperpeerStorageStatusResponse.class).getStatus();
        } catch (final NetworkException e) {
            // #if LOGGER >= ERROR
            LOGGER.error("Getting superpeer 0x%X storage status failed", superpeer);
            // #endif /* LOGGER >= ERROR */
            statusArray[i] = null;
        }

        m_overlayLock.readLock().lock();
    }
    m_overlayLock.readLock().unlock();

    // aggregate status...bad performance =(
    ArrayList<Long> aggregatedStatus = new ArrayList<>();
    for (SuperpeerStorage.Status aStatusArray : statusArray) {
        ArrayList<Long> toMergeArray = aStatusArray.getStatusArray();
        toMergeArray.stream().filter(val -> !aggregatedStatus.contains(val)).forEach(aggregatedStatus::add);
    }

    // and finally...sort
    aggregatedStatus.sort((p_o1, p_o2) -> {
        Integer i1 = (int) (p_o1 >> 32);
        Integer i2 = (int) (p_o2 >> 32);

        return i1.compareTo(i2);
    });

    return new SuperpeerStorage.Status(statusArray[0].getMaxNumItems(), statusArray[0].getMaxStorageSizeBytes(), aggregatedStatus);
}
 
Example 15
Project: intellij-plugin   File: SeedStackGroupNode.java   Source Code and License Vote up 4 votes
@Override
protected final List<T> doGetChildren() {
    ArrayList<T> result = new ArrayList<>(children.values());
    result.sort(SeedStackStructure.NODE_COMPARATOR);
    return result;
}
 
Example 16
Project: BaseClient   File: Arraylist.java   Source Code and License Vote up 4 votes
@EventTarget
public void onRender(EventRender2D e) {
	/*if (flagTime.hasReached(changeTime)) {
		colorFlag = ! colorFlag;
		flagTime.reset();
	}
	blueColor = colorFlag ? blueColor - 0.05f * (fpsTimeHelper.getCurrentMS() - fpsTimeHelper.getLastMS()): blueColor + 0.5f * (fpsTimeHelper.getCurrentMS() - fpsTimeHelper.getLastMS());
	if (blueColor > 255) blueColor = 255;
	else if (blueColor < 100) blueColor = 100;
	hud.drawStringWithShadow("test", 90, 4, new Color(0, 0, (int)blueColor, 255).getRGB());*/


	if (!client.getManagers().getManager(SettingManager.class).getSetting(HUD.class, "ArrayList")
			.getBooleanValue()) {
		ArrayList<Module> mods = client.getManagers().getManager(ModuleManager.class).getVisibleMods();

		mods.sort((o1, o2) -> hud.getStringWidth(o2.getName()) - hud.getStringWidth(o1.getName()));
		int y = pos == DrawPos.TOP ? 2 : e.height - hud.getHeight();
		float tempX = 0;
		for (Module m : mods) {
			m.anim = m.anim + hud.getStringWidth(m.getName()) / speed
							* (fpsTimeHelper.getCurrentMS() - fpsTimeHelper.getLastMS());
			if (m.anim > hud.getStringWidth(m.getName())) m.anim = hud.getStringWidth(m.getName());

			RenderUtils.drawRect(e.width - m.anim - 5, y - 2, e.width - 1, y + (hud.getHeight()),
					ColorUtils.backColor);
			RenderUtils.drawRect(e.width - m.anim - 5 - 1, y - 2, e.width - m.anim - 5, y + (hud.getHeight()) + 1,
					ColorUtils.arrayColor);
			RenderUtils.drawRect(e.width - 1, y - 2, e.width, y + (hud.getHeight()), ColorUtils.arrayColor);
			RenderUtils.drawRect(e.width - tempX - 5, pos == DrawPos.TOP ? y - 2 : y + hud.getHeight(),
					e.width - m.anim - 5, pos == DrawPos.TOP ? y - 1 : y + hud.getHeight() + 1,
					ColorUtils.arrayColor);
			hud.drawStringWithShadow(m.getName(), e.width - m.anim - 3, y + 1, ColorUtils.arrayColor);
			tempX = m.anim;
			y = pos == DrawPos.TOP ? y + hud.getHeight() + 2 : y - hud.getHeight() - 2;
		}

		if (mods.size() != 0) {
			RenderUtils.drawRect(e.width - mods.get(0).anim - 5 - 1f, pos == DrawPos.TOP ? 0 : e.height, e.width,
					pos == DrawPos.TOP ? 1 : e.height - 1, ColorUtils.arrayColor);
			RenderUtils.drawRect(e.width - tempX - 5 - 1f, pos == DrawPos.TOP ? y - 2 : y + hud.getHeight(),
					e.width, pos == DrawPos.TOP ? y - 1 : y + hud.getHeight() + 1, ColorUtils.arrayColor);
		}

		fpsTimeHelper.reset();
	}

}
 
Example 17
Project: openjdk-jdk10   File: BiDirectionalTraceBuilder.java   Source Code and License Vote up 4 votes
private static Deque<AbstractBlockBase<?>> createQueue(AbstractBlockBase<?>[] blocks) {
    ArrayList<AbstractBlockBase<?>> queue = new ArrayList<>(Arrays.asList(blocks));
    queue.sort(BiDirectionalTraceBuilder::compare);
    return new ArrayDeque<>(queue);
}
 
Example 18
Project: Aardvark   File: GUI_fragment_graph.java   Source Code and License Vote up 4 votes
private void calculateCipherIC(int n)
{
    cipherIC = getCipherIC(cipherText);

    cipherICTV.setText("[IC: " + Double.toString(cipherIC) + "]\n");

    cipherICofN = new ArrayList<Double>();

    ArrayList<mPair<Integer, Double>> averageICList = new ArrayList<>();

    /**calculate IC of period 2...n*/
    for(int i = 2; i < n; i++)
    {
        double averageIC = 0;

        cipherICofN = getCipherIC(cipherText, i);
        for(int x = 0; x < cipherICofN.size(); x++)
        {
            averageIC += cipherICofN.get(x);
        }

        averageIC = averageIC/i;

        //averageIC control: if its 0, dont display
        if(averageIC != 0)
            averageICList.add(new mPair(i, averageIC));
    }

    //sort the average IC list (DESCENDING)
    averageICList.sort(new Comparator<mPair<Integer, Double>>()
    {
        @Override
        public int compare(mPair<Integer, Double> t0, mPair<Integer, Double> t1) {
            return t1.second.compareTo(t0.second);
        }
    });

    //append the texts to the interface
    for(int i = 0; i < averageICList.size(); i++)
        cipherICTV.append("IC of period " + (averageICList.get(i).first) + ": " + new DecimalFormat("0.0000").format(averageICList.get(i).second) + "\n");

    cipherICTV.setMovementMethod(ScrollingMovementMethod.getInstance());
}
 
Example 19
Project: xcc   File: SubtargetEmitter.java   Source Code and License Vote up 4 votes
/**
 * Produces a subtarget specific function for parsing
 * the subtarget features string.
 * @param os
 */
private void parseFeaturesFunction(PrintStream os) throws Exception
{
    ArrayList<Record> features = records.getAllDerivedDefinition("SubtargetFeature");
    features.sort(LessRecord);

    os.printf("\t/**\n");
    os.printf("\t * Parses features string setting specified subtarget options.\n");
    os.println("\t */");
    os.println("\tpublic String parseSubtargetFeatures(String fs, String cpu) {");
    os.println("\t\tSubtargetFeatures features = new SubtargetFeatures(fs);");
    os.println("\t\tfeatures.setCPUIfNone(cpu);");
    os.println("\t\tint bits = features.getBits(subTypeKV,featureKV);");

    for (int i = 0; i < features.size(); i++)
    {
        Record r = features.get(i);
        String instance = r.getName();
        String value = r.getValueAsString("Value");
        String attribute = r.getValueAsString("Attribute");

        if (value.equals("true") || value.equals("false"))
        {
            os.printf("\t\tif ((bits & %s) != 0)\n", instance);
            os.printf("\t\t\t%s = %s;\n", attribute, value);
        }
        else
        {
            os.printf("\t\tif ((bits & %s) != 0 && %s.compareTo(%s) < 0)\n",
                    instance, attribute, value);
            os.printf("\t\t\t%s = %s;\n", attribute, value);
        }
    }

    if (hasItrineraries)
    {
        os.println();
        os.print("\t\tInstrItinerary itinerary = (InstrItinerary)" +
                "\t\tfeatures.getInfo(procItinKV);\n" +
                "\t\tInstrItins = instrItineraryData(stages, operandCycles, itinerary);\n");
    }

    os.printf("\t\treturn features.getCPU();\n\t}\n\n");
}
 
Example 20
Project: grittier_ext   File: Likes.java   Source Code and License Vote up 4 votes
@GET
public Response getLikes(@PathParam("username") final String username,
                         @QueryParam("limit") @DefaultValue("25") final Integer limit,
                         @QueryParam("since") final Long since,
                         @QueryParam("username2") final String username2,
                         @Context GraphDatabaseService db) throws IOException {
    ArrayList<Map<String, Object>> results = new ArrayList<>();
    Long latest = getLatestTime(since);

    try (Transaction tx = db.beginTx()) {
        Node user = Users.findUser(username, db);
        Node user2 = null;
        if (username2 != null) {
            user2 = Users.findUser(username2, db);
        }
        for (Relationship r1 : user.getRelationships(Direction.OUTGOING, RelationshipTypes.LIKES)) {
            Node post = r1.getEndNode();
            Map<String, Object> properties = post.getAllProperties();
            Long time = (Long)r1.getProperty("time");
            if(time < latest) {
                Node author = getAuthor(post, (Long)properties.get(TIME));
                properties.put(LIKED_TIME, time);
                properties.put(USERNAME, author.getProperty(USERNAME));
                properties.put(NAME, author.getProperty(NAME));
                properties.put(HASH, author.getProperty(HASH));
                properties.put(LIKES, post.getDegree(RelationshipTypes.LIKES));
                properties.put(REPOSTS, post.getDegree() - 1 - post.getDegree(RelationshipTypes.LIKES));
                if (user2 != null) {
                    properties.put(LIKED, userLikesPost(user2, post));
                    properties.put(REPOSTED, userRepostedPost(user2, post));
                }
                results.add(properties);
            }
        }
        tx.success();
    }

    results.sort(Comparator.comparing(m -> (Long) m.get(LIKED_TIME), reverseOrder()));

    return Response.ok().entity(objectMapper.writeValueAsString(
            results.subList(0, Math.min(results.size(), limit))))
            .build();
}