Given two lists: one with names and the other with values. Each element of the first list is associated with an element of the second. It is necessary to sort the names from the first list in ascending and descending alphabetical order, and print them with their respective value from the second list.
I've done it this way, but it doesn't sort alphabetically.
import java.util.ArrayList;
import java.util.HashSet;
public class Logic {
public static void studList() {
ArrayList<String> stud = new ArrayList<>();
ArrayList<Double> uspe = new ArrayList<>();
stud.add("Peter");
stud.add("Sophia");
stud.add("Jacob");
stud.add("Matt");
stud.add("Hannah");
uspe.add(4.5);
uspe.add(6.3);
uspe.add(3.8);
uspe.add(5.5);
uspe.add(4.7);
ArrayList<String> list = sortA(stud,uspe);
for (String s:list) {
View.printer(s);
}
View.printer("-");
for (int i = list.size()-1; i >= 0; i--) {
String s = list.get(i);
View.printer(s);
}
}
private static ArrayList<String> sortA(ArrayList<String> st, ArrayList<Double> us) {
ArrayList<String> list = new ArrayList<>();
String s;
for (int i = 0; i < st.size(); i++) {
s = st.get(i) + ": " + us.get(i);
list.add(s);
}
HashSet<String> set = new HashSet<>(list);
list.clear();
list.addAll(set);
return list;
}
}
uses
Now that I see it, I would recommend you to create an object with both data since one is related to another
You create a list of your object
And to order it for example by name
And then
You can use the bubble method which is the easiest sorting method.
A Java ArrayList can be sorted using the sort() method of java.util.Collections .
If the ArrayList contains literals (Strings, int, char, ...) and you want to sort in ascending order, just do:
Example:
whose output is: