當前位置: 首頁>>代碼示例>>Java>>正文


Java ArrayList.sort方法代碼示例

本文整理匯總了Java中java.util.ArrayList.sort方法的典型用法代碼示例。如果您正苦於以下問題:Java ArrayList.sort方法的具體用法?Java ArrayList.sort怎麽用?Java ArrayList.sort使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.util.ArrayList的用法示例。


在下文中一共展示了ArrayList.sort方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: onCreate

import java.util.ArrayList; //導入方法依賴的package包/類
@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);

}
 
開發者ID:lanceeeaton,項目名稱:Text-Rabbit,代碼行數:26,代碼來源:Highscores_Standard.java

示例2: onCreate

import java.util.ArrayList; //導入方法依賴的package包/類
@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);
}
 
開發者ID:lanceeeaton,項目名稱:Text-Rabbit,代碼行數:25,代碼來源:Highscores_Classic.java

示例3: parse

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:cocolocomoco21,項目名稱:ULCRS,代碼行數:32,代碼來源:DataParse.java

示例4: addCardsToJson

import java.util.ArrayList; //導入方法依賴的package包/類
@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);
}
 
開發者ID:slavetto,項目名稱:anki-cards-web-browser,代碼行數:26,代碼來源:DeckWithCategories.java

示例5: sortVillages

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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;
        });
    }
}
 
開發者ID:ternsip,項目名稱:StructPro,代碼行數:15,代碼來源:Structures.java

示例6: openLocals

import java.util.ArrayList; //導入方法依賴的package包/類
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;
}
 
開發者ID:inferjay,項目名稱:r8,代碼行數:11,代碼來源:JarState.java

示例7: getOrder

import java.util.ArrayList; //導入方法依賴的package包/類
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;
}
 
開發者ID:ruananswer,項目名稱:twitter-anomalyDetection-java,代碼行數:16,代碼來源:DetectAnoms.java

示例8: getSortedPlayers

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:riddlesio,項目名稱:hack-man-2-engine,代碼行數:16,代碼來源:AbstractEnemyAI.java

示例9: createSortedImportList

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 
 */
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;
}
 
開發者ID:annoflex,項目名稱:annoflex,代碼行數:16,代碼來源:ImportInserter.java

示例10: emitProcessorLookup

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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("};");
}
 
開發者ID:JianpingZeng,項目名稱:xcc,代碼行數:33,代碼來源:SubtargetEmitter.java

示例11: createAndSaveEmoticonRegex

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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());
}
 
開發者ID:kevalpatel2106,項目名稱:EmoticonGIFKeyboard,代碼行數:20,代碼來源:Main.java

示例12: pre

import java.util.ArrayList; //導入方法依賴的package包/類
@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);
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:47,代碼來源:CryptoBulkFeature.java

示例13: sortPresentations

import java.util.ArrayList; //導入方法依賴的package包/類
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());
}
 
開發者ID:ulriknyman,項目名稱:H-Uppaal,代碼行數:7,代碼來源:ProjectPaneController.java

示例14: superpeerStorageGetStatus

import java.util.ArrayList; //導入方法依賴的package包/類
/**
 * 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);
}
 
開發者ID:hhu-bsinfo,項目名稱:dxram,代碼行數:46,代碼來源:OverlayPeer.java

示例15: doGetChildren

import java.util.ArrayList; //導入方法依賴的package包/類
@Override
protected final List<T> doGetChildren() {
    ArrayList<T> result = new ArrayList<>(children.values());
    result.sort(SeedStackStructure.NODE_COMPARATOR);
    return result;
}
 
開發者ID:seedstack,項目名稱:intellij-plugin,代碼行數:7,代碼來源:SeedStackGroupNode.java


注:本文中的java.util.ArrayList.sort方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。