I have an object that holds an int value, a String, and a double. Instances of that object are stored in an ArrayList. I want to print that object now but I want to first sort the ArrayList by the String values. I am having a hard time conceptualizing how I'd do that through something like a selection sort. Any help would be grateful!
我有一个包含int值,String和double的对象。该对象的实例存储在ArrayList中。我想现在打印该对象,但我想首先按字符串值对ArrayList进行排序。我很难通过类似选择的方式概念化我是如何做到这一点的。任何帮助将不胜感激!
Here is what I thought you were suppose to do, but that didn't seem to work.
这是我认为你想做的事情,但这似乎不起作用。
public static void sSortStrings(ArrayList<Student> list) { //Selection sort
int count1;
int count2;
int largest;
String temp;
for (count1 = 0; count1 < list.size() - 1; count1++) {
largest = 0;
for (count2 = largest + 1; count2 < list.size() - count1; count2++) {
if (list[largest].compareTo(list[count2]) < 0) {
largest = count2;
}
}
temp = list[list.size() - 1 - count1];
list[list.size() - 1 - count1] = list[largest];
list[largest] = temp;
}
}
Just to throw in there my professor had included this in the source code, but I'm not sure if I should be calling it instead of the compare to method
只是为了扔进去,我的教授已将其包含在源代码中,但我不确定是否应该调用它而不是比较方法
public boolean nameComesBefore(Student other) {
return name.compareToIgnoreCase(other.name) < 0;
}
1 个解决方案
#1
0
Assuming the Student
class has getter for the String property. Then all you need to do to sort the list islist.sort(Comparator.comparing(Student::getName))
假设Student类具有String属性的getter。然后你需要做的就是列表的排序是list.sort(Comparator.comparing(Student :: getName))
This will sort the given list by student's name. For more options check javadoc for List.sort() and Comparator.
这将按学生的姓名对给定列表进行排序。有关更多选项,请检查List.sort()和Comparator的javadoc。
#1
0
Assuming the Student
class has getter for the String property. Then all you need to do to sort the list islist.sort(Comparator.comparing(Student::getName))
假设Student类具有String属性的getter。然后你需要做的就是列表的排序是list.sort(Comparator.comparing(Student :: getName))
This will sort the given list by student's name. For more options check javadoc for List.sort() and Comparator.
这将按学生的姓名对给定列表进行排序。有关更多选项,请检查List.sort()和Comparator的javadoc。