Sort arraylist arraylist integers

I am looking for sorting arraylist arraylist integers and I need help?

I was informed that I need to implement a comparator or match, and then use collection.sort to sort the list of the list in order ...

ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>() If you look at the list of list as the following example: C1 – 5,4,10 C2 – 3,2,1 C3 – 7,8,6 First it will be sorted like this: C1 – 4,5,10 C2 – 1,2,3 C3 – 6,7,8 Then it will be sorted like this C1 – 1,2,3 C2 – 4,5,6 C3 – 7,8,10 
+4
source share
3 answers

There are no errors for null lists, but here it is.

 List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); for (List<Integer> l : list) { Collections.sort(l); } Collections.sort(list, new Comparator<List<Integer>>() { public int compare(List<Integer> o1, List<Integer> o2) { return o1.get(0).compareTo(o2.get(0)); } }); System.out.println(list); 

With Java 8, it becomes even more concise:

 List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4), Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6)); list.forEach(Collections::sort); Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0))); System.out.println(list); 
+15
source

You can simply sort each list individually. Collections.sort(collection) automatically sorts integers in ascending order.

+6
source

If the sorting does not have what you need, you can try this algorithm:

 package drawFramePackage; import java.awt.geom.AffineTransform; import java.util.ArrayList; import java.util.ListIterator; import java.util.Random; public class QuicksortAlgorithm { ArrayList<AffineTransform> affs; ListIterator<AffineTransform> li; Integer count, count2; /** * @param args */ public static void main(String[] args) { new QuicksortAlgorithm(); } public QuicksortAlgorithm(){ count = new Integer(0); count2 = new Integer(1); affs = new ArrayList<AffineTransform>(); for (int i = 0; i <= 128; i++){ affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0)); } affs = arrangeNumbers(affs); printNumbers(); } public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){ while (list.size() > 1 && count != list.size() - 1){ if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){ list.add(count, list.get(count2)); list.remove(count2 + 1); } if (count2 == list.size() - 1){ count++; count2 = count + 1; } else{ count2++; } } return list; } public void printNumbers(){ li = affs.listIterator(); while (li.hasNext()){ System.out.println(li.next()); } } } 
+1
source

Source: https://habr.com/ru/post/1414823/


All Articles