本文整理汇总了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);
}
示例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);
}
示例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);
}
示例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);
}
示例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;
});
}
}
示例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;
}
示例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;
}
示例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;
}
示例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;
}
示例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("};");
}
示例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());
}
示例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);
}
示例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());
}
示例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);
}
示例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;
}