java: TreeSet order - java

With this code I get this output:
TreeSet<String> t=new TreeSet<String>();
t.add("test 15");
t.add("dfd 2");
t.add("ersfd 20");
t.add("asdt 10");
Iterator<String> it=t.iterator();
while(it.hasNext()){
System.out.println(it.next);
}
I get:
asdt 10
dfd 2
ersfd 20
test 15
How can I get an order of this kind, based on the numbers, with TreeSet?
dfd 2
asdt 10
test 15
ersfd 20

The TreeSet implementation is sorting by the lexicographic order of the string values you insert. If you want to sort by the integer value, then you'll need to do as these others suggested and create a new object and override the compareTo method, or use your own comparator.
Set<String> set = new TreeSet<String>(new Comparator<String>() {
public int compare(String one, String other) {
// implement
}
});
or
public class MyClass implements Comparable {
private String key;
private int value;
public int compareTo(MyClass other) {
// implement
}
public boolean equals(MyClass other) {
// implement
}
// snip ...
}
Set<MyClass> set = new TreeSet<MyClass>();

You can use one of the TreeSet constructors: http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html#TreeSet%28java.util.Comparator%29
This allows you to specify your own comparator that allows you to organize the entries in the Set however you like.
Implement a Comparator that extracts the number from the String and then sorts by the number first, only falling back to a String comparison if both numbers are equal.

Use the TreeSet constructor that receives a custom Comparator, and implement a Comparator that sorts the string differently.
Here's an example (untested, check the code before using):
TreeSet<String> t = new TreeSet<String>(new Comparator<String>() {
public int compare(String s1, String s2) {
int spaceIndex1 = s1.indexOf(' ');
int spaceIndex2 = s2.indexOf(' ');
return Integer.parseInt(s1.substring(spaceIndex1 + 1)).compareTo(Integer.parseInt(s2.spaceIndex2 + 1));
}
});

Using lambda
Set<String> set = new TreeSet<String>(
(o1, o2) -> String.format("%3s", o1.substring( o1.indexOf(" ") + 1)).replace(" ","0")
.compareTo( String.format("%3s", o2.substring( o2.indexOf(" ") + 1)).replace(" ","0")
));
set.add("test 15");
set.add("dfd 2");
set.add("ersfd 20");
set.add("asdt 10");
set.stream().forEach(s -> System.out.println(s));
result:
dfd 2
asdt 10
test 15
ersfd 20
But I strongly recommend separe the significant values (in this case integers) in other key estucture. for easy manipulation.

Try this:
TreeSet set = new TreeSet(new Comparator<String>(){
public int compare(String o1, String o2){
String n1 = o1.split(" ")[1];
String n2 = o2.split(" ")[1];
return Integer.parse(n2) - Integer.parse(n1);
}
public boolean equals(String o1, String o2){
return compare(o1,o2)==0;
}
});

class Book implements Comparable<Book> {
String name;
int id;
public Book(String name,int id) {
this.name = name;
this.id = id;
}
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class TreeSet2 {
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book("test", 15);
Book b2=new Book("dfd", 2);
Book b3=new Book("ersfd", 20);
Book b4=new Book("asdt", 10);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
set.add(b4);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.name+" "+b.id);
}
}
}

import java.util.ArrayList;
import java.util.*;
import java.util.Arrays;
class SecondHighest {
public static void main(String[] args) {
int i;
int a[]={2,3,4,5,7,6,9,9,9,8,8,7};
int total=a.length;
Arrays.sort(a);
TreeSet<Integer> set=new TreeSet<Integer>();
for(i=0;i<total;i++)
{
set.add(a[i]);
}
System.out.println(set.last()-1);
Iterator<Integer> itr=set.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
This is a program related to find the second largest element in array. I have used Tree-set for sorting purpose. Using tree-set we can remove all the repeated elements.
After sorting element using set method.There is a function set.last() by which you can find the last element of array or list.
I applied set.last()-1 function that gives me second largest element in array.

Related

sorting on the basis on a column not alphabetically

I have a bean called vulnerability. It is having a column "severity".
private String severity;
Severity can hold string value High,Medium and Low. Now whenever sorting of this bean on the basis of severity column is done it happens alphabetically i.e. High,Low and Medium. But i want the sorting to happen high,medium, low when descending and low, medium,high when ascending.
I was seeing comparator to make this custom sorting but it needs to cover lots of cases. Isn't their any other way?
You can (and should) use an enum - not a String nor a int:
enum Severity {
LOW, MEDIUM, HIGH;
}
Usage:
List<Severity> lst = new ArrayList<Severity>();
lst.add(Severity.MEDIUM);
lst.add(Severity.LOW);
lst.add(Severity.HIGH);
for (Severity s : lst)
System.out.println("s = " + s);
Collections.sort(lst);
System.out.println();
for (Severity s : lst)
System.out.println("s = " + s);
OUTPUT:
s = MEDIUM
s = LOW
s = HIGH
s = LOW
s = MEDIUM
s = HIGH
EDIT
Since the OP says he can't modify the usage of Strings, we can map the strings into a comparable values:
static Map<String, Integer> severities = new HashMap<String, Integer>();
static {
severities.put("LOW",1);
severities.put("MEDIUM",2);
severities.put("HIGH",3);
}
public static void main(String[] args) {
List<String> lst = new ArrayList<String>();
lst.add("MEDIUM");
lst.add("LOW");
lst.add("HIGH");
for (String s : lst)
System.out.println("s = " + s);
Collections.sort(lst, new Comparator<String>() {
public int compare(String a1, String a2) {
Integer v1 = severities.get(a1);
Integer v2 = severities.get(a2);
return v1.compareTo(v2);
}
});
System.out.println();
for (String s : lst)
System.out.println("s = " + s);
}
and if you want to order the items in descending order you can sort and then reverse:
Collections.sort(lst);
Collections.reverse(lst);
There is an implicit compareTo operator defined on enums, which takes their declaration order to mean "smaller than". No additional code is needed.
enum Severity { Low, Medium, High }
Low.compareTo(High); // returns -1
Medium.compareTo(Low); // returns 1
However, note that the names of the enum constants will be those printed by toString() (and therefore visible to users if you echo enums directly) - if you want to use different internal and external names, possibly to uphold code conventions (say, all-caps-constants), then you will need to add an enum constructor and override the enum's toString method to use the passed-in constructor attribute.
If you cannot use enums, and you cannot change your bean
Then build a Comparator for it:
public class SeverityComparator implements Comparator<String> {
private int direction;
public SeverityComparator(boolean reverse) {
this.direction = reverse ? -1 : 1;
}
private int severity(String s) {
if (s.equals("Low")) { // you really should have constants for the values...
return 0;
} else if (s.equals("Medium")) {
return 1;
} else if (s.equals("High")) {
return 2;
} else {
throw new IllegalArgumentException("Not a severity: " + s);
}
}
#Override
public int compareTo(String other) {
return direction * (severity(this) - severity(other));
}
}
Use as
Collections.sort(listOfSeverities, new SeverityComparator(false)); // ascending
Collections.sort(listOfSeverities, new SeverityComparator(true)); // descending
#alfasin answer is correct but i would suggest using guava's Ordering:
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import javax.annotation.Nullable;
import java.util.List;
public class SeveritySortTest {
private static final List<Severity> SEVERITY_LIST = ImmutableList.copyOf(Severity.values());
public static void main(String[] args) {
Ordering<Severity> severityOrdering = Ordering.natural().onResultOf(new Function<Severity, Integer>() {
#Nullable
#Override
public Integer apply(#Nullable Severity input) {
return input.getSeverity();
}
});
List<Severity> sortedAscending = severityOrdering.sortedCopy(SEVERITY_LIST);
List<Severity> sortedDescending = severityOrdering.reverse().sortedCopy(SEVERITY_LIST);
}
enum Severity {
LOW(1), MEDIUM(2), HIGH(3);
private int severity;
Severity(int s) {
severity = s;
}
int getSeverity() {
return severity;
}
}
}
Working Solution:
Collections.sort(recommendations, new Comparator() {
private int priority(String s) {
if (s.equalsIgnoreCase("Low")) {
return 1;
} else if (s.equalsIgnoreCase("Medium")) {
return 2;
} else if (s.equalsIgnoreCase("High")) {
return 3;
} else {
return 0;
}
}
#Override
public int compare(Recommendation o1, Recommendation o2) {
return -1 * (priority(o1.getPriority()) - priority(o2.getPriority()));
}
});
If you want the DB to do this through JPA/Hibernate you could create a sort expression based on a simple case statement, assuming your entity is called Case:
Expression exp = criteriaBuilder.selectCase(root.get(Case_.priority)).when("High", 1).when("Medium", 2).otherwise(3);
queryBuilder.orderBy(orderDir.isAscending() ? criteriaBuilder.asc(exp) : criteriaBuilder.desc(exp));
Using case statements in an order by clause isn't great for performance, but solves it. Works with Oracle.

how do you sort group of arrays that are paired to each other?

how do you sort group of arrays that are paired to each other?
for example is that if you have an array of student numbers and student names. how can i make student names adjust too. when you sort it by student number?
example output of what i wanted to be:
unsorted:
ID numbers name course
5 jomar IT
3 karen CS
sorted (by ID numbers)
ID numbers name course
3 karen CS
5 jomar IT
I've tried to use TreeMap but there's this problem that if the value of ID numbers are the same, it will overwrite the other and it will print like this:
sorted (by ID numbers)
ID numbers name course
3 karen CS
in reply to Stultuske
i tried to use 1 array that contains id num, name, course.
its like this:
for(int i=0;i<array.length;i++){
String [][] storeAllArray = {{array[i]},{array2[i]},{array3[i]}};
System.out.println(storeAllArray[0][0] + " "
+ storeAllArray[1][0] + " "
+ storeAllArray[2][0]);
}
public class Student implements Comparable {
private int id;
private String name;
private String course;
public Student(int pid, int pname, int pcourse) {
id = pid;
name = pname;
course = pcourse;
}
#Override
public int compareTo(Object o) {
return new Integer(id).compareTo(new Integer(((Student)o).getID()));
}
public int getID() { return id; }
public String getName() { return name; }
public String getCourse() { return course; }
}
At that point, you just make an ArrayList (Or whatever collection you like) of Students, and call Collections.sort(~initialized ArrayList~);
If you had a Collection<Student>, you'd sort it like this:
Collections.sort(studentList,new Comparator<Student>() {
int compareTo(Student s1, Student s2) {
return s1.getSomeField().compareTo(s2.getSomeField());
)
});
Basically you pass a Comparator (generated inline here) to Collections.sort()
I'd highly recommend against the parallel array version since it's really avoiding the OO nature of Java.
But if you REALLY want to do it, you'd have to have a third array that is just the indexes from 1 to number of elements in your array, then you'd have to use a parallel index array and sort it using Arrays.sort() with a Comparator that compares your parallel array's values (instead of the index array) and then you iterator over the sorted index array and print out the elements that match the index of the other array... Really much easier to do it correctly as above.
Part 1: Define your Comparator as following:
public class MyComparator implements Comparator<Object[]> {
#Override
public int compare( Object[] o1, Object[] o2 ) {
if ( (int) o1[0] > (int) o2[0] )
return 1;
else if ( !((int) o1[0] > (int) o2[0]) )
return -1;
else
return 0;
}
}
Part 2: And then follow my example code below in your main class:
public class MyComparatorTest {
public static void main( String[] args ) {
List<Object[]> list = new ArrayList<Object[]>();
Object[] o = new Object[3];
o[0] = 2;
o[1] = "TWO";
o[2] = "RR";
list.add(o);
o = new Object[3];
o[0] = 3;
o[1] = "THREE";
o[2] = "GG";
list.add(o);
o = new Object[3];
o[0] = 1;
o[1] = "ONE";
o[2] = "TT";
list.add(o);
// This sorts your list
Collections.sort(list, new MyComparator());
// The following loop is only to show you the sorted list content.
for (Object[] obj : list) {
for (Object obj2 : obj) {
System.out.print(" " + obj2);
}
System.out.println();
}
}
}
Sample output is:
1 ONE TT
2 TWO RR
3 THREE GG

Sorting PriorityQueue

I am having a problem with PriorityQueues, as I am lead to believe it orders on priority however I am not sure what the priority is (I mean what the value is and where it comes from). A priorityQueue can be made with a comparator in the constructor and I have tried this but it does not work.
Queue class:
public JavaPriorityFlightQueue() {
super();
flights = new PriorityQueue(5, new SortQueueViaPriority());
}
Comparator:
import java.util.Comparator;
public class SortQueueViaPriority implements Comparator {
public int compare(Object o1, Object o2){
Flight f1 = (Flight) o1;
Flight f2 = (Flight) o2;
if( f1 == null || f2 == null ){
if( f1 == f2 ) return 0;
else if( f2 == null) return +1;
else return -1;
}
Integer i1 = (Integer) f1.getPriority();
Integer i2 = (Integer) f2.getPriority();
return i2.compareTo(i1);
}
}
Priority is an int value which is part of the flight class. I test this.
JavaPriorityFlightQueue flightQueue = new JavaPriorityFlightQueue();
Flight flight1 = new Flight("0001",9);
Flight flight2 = new Flight("0002",7);
Flight flight3 = new Flight("0003",1);
Flight flight4 = new Flight("0004",2);
Flight flight5 = new Flight("0005",1);
However the PriorityQueue is not sorted, and when I check it the value 9 is never compared to anything and the result is nothing is sorted. the compare class SortQueueViaPriority is copy and pasted from another class where the class sorts perfectly.
I suggest you try the following example. If you use PriorityQueue as a queue, the entries are removed in order.
import java.util.Comparator;
import java.util.PriorityQueue;
public class Main {
public static void main(String... args) {
PriorityQueue<Flight> flights = new PriorityQueue<Flight>(5, new SortQueueViaPriority());
flights.add(new Flight("0001", 9));
flights.add(new Flight("0002", 7));
flights.add(new Flight("0003", 1));
flights.add(new Flight("0004", 2));
flights.add(new Flight("0005", 1));
while (!flights.isEmpty())
System.out.println(flights.remove());
}
}
class SortQueueViaPriority implements Comparator<Flight> {
#Override
public int compare(Flight f1, Flight f2) {
return Integer.compare(f2.getPriority(), f1.getPriority());
}
}
class Flight {
private final String name;
private final int priority;
Flight(String name, int priority) {
this.name = name;
this.priority = priority;
}
public int getPriority() {
return priority;
}
#Override
public String toString() {
return "Flight{" +
"name='" + name + '\'' +
", priority=" + priority +
'}';
}
}
prints
Flight{name='0001', priority=9}
Flight{name='0002', priority=7}
Flight{name='0004', priority=2}
Flight{name='0003', priority=1}
Flight{name='0005', priority=1}
Note: PriorityQueue sorts entries such that only the first element will be the smallest. If you iterate over the queue, you will see all the elements, but they may or may not be in order.
Issue is Iterator.As Documented in Java doc of PriorityQueue#iterator
Returns an iterator over the elements in this queue. The iterator does not return the elements in any particular order.
As toString uses iterator it will not get printed in order. Or if you use loop based on iterator then also it will be in order.
And in the Java doc of PriorityQueue
The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue.
To get results in order you will have to use one of these methods.
Instead of Comparator just use Comparable interface.
Your Flight class should implement Comparable interface. Then you need to override the compareTo() method. In that method you can add your own logic for sorting based on the property you need.
Just like this way:
#Override
public int compareTo(Object obj) {
// TODO Auto-generated method stub
Flight f = (Flight)obj;
if(this.a <f.a){
return 1;
}else{
return -1;
}
}

Sorting 2D array of strings in Java

I know that this question might have been asked before, but I was not able to find a fit answer. So say I have this array:
String[][] theArray = {
{"james", "30.0"},
{"joyce", "35.0"},
{"frank", "3.0"},
{"zach", "34.0"}};
Is there a way to descendingly sort this array by the second element of each sub-element. So I would get something like this.
theArray = {
{"joyce", "35.0"},
{"zach", "34.0"},
{"james", "30.0"},
{"frank", "3.0"}};
Use Arrays.sort(arr, comparator) with a custom comparator:
Arrays.sort(theArray, new Comparator<String[]>(){
#Override
public int compare(final String[] first, final String[] second){
// here you should usually check that first and second
// a) are not null and b) have at least two items
// updated after comments: comparing Double, not Strings
// makes more sense, thanks Bart Kiers
return Double.valueOf(second[1]).compareTo(
Double.valueOf(first[1])
);
}
});
System.out.println(Arrays.deepToString(theArray));
Output:
[[joyce, 35.0], [zach, 34.0], [james, 30.0], [frank, 23.0]]
Beware:
you will be sorting the array you passed in, Arrays.sort() will not return a new array (in fact it returns void). If you want a sorted copy, do this:
String[][] theCopy = Arrays.copyOf(theArray, theArray.length);
And perform the sorting on theCopy, not theArray.
You must use the Arrays.sort() method. This method takes a Comparator as argument. The sort method delegates to the comparator to determine if one element of the array must be considered bigger, smaller or equal to another element. Since every element of the outer array is an array, the comparator will have to compare arrays (of Strings).
The arrays must be compared based on the value of their second element. This second element is a String which in fact represents a double number. So you'll have to transorm the strings into numbers, else the order will be lexicographical (20 come before 3) rather than numerical.
The comparator could thus look like this :
public class StrinArrayComparator implements Comparator<String[]> {
#Override
public int compare(String[] array1, String[] array2) {
// get the second element of each array, andtransform it into a Double
Double d1 = Double.valueOf(array1.[1]);
Double d2 = Double.valueOf(array2.[1]);
// since you want a descending order, you need to negate the
// comparison of the double
return -d1.compareTo(d2);
// or : return d2.compareTo(d1);
}
}
If you want to move away from arrays, here's a variation that uses List<Record> and a RecordComparator that implements Comparator<Record>.
Console:
joyce 35.0
zach 34.0
james 30.0
frank 23.0
Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/** #see http://stackoverflow.com/questions/5064027 */
public class ComparatorTest {
public static void main(String[] args) {
List<Record> list = new ArrayList<Record>(Arrays.asList(
new Record("james", "30.0"),
new Record("joyce", "35.0"),
new Record("frank", "23.0"),
new Record("zach", "34.0")));
print(list, Sort.DESCENDING, Field.D);
}
private static void print(List<Record> list, Sort s, Field f) {
RecordComparator rc = new RecordComparator(s, f);
Collections.sort(list, rc);
for (Record r : list) {
System.out.println(r);
}
}
}
class Record {
private String s;
private Double d;
public Record(String name, String number) {
this.s = name;
this.d = Double.valueOf(number);
}
#Override
public String toString() {
return s + " " + d;
}
public int compareTo(Field field, Record record) {
switch (field) {
case S: return this.s.compareTo(record.s);
case D: return this.d.compareTo(record.d);
default: throw new IllegalArgumentException(
"Unable to sort Records by " + field.getType());
}
}
}
enum Sort { ASCENDING, DESCENDING; }
enum Field {
S(String.class), D(Double.class);
private Class type;
Field(Class<? extends Comparable> type) {
this.type = type;
}
public Class getType() {
return type;
}
}
class RecordComparator implements Comparator<Record> {
private Field field;
private Sort sort;
public RecordComparator(Sort sort, Field field) {
this.sort = sort;
this.field = field;
}
#Override
public final int compare(Record a, Record b) {
int result = a.compareTo(field, b);
if (sort == Sort.ASCENDING) return result;
else return -result;
}
}
You seem to be living in object denial. Those inner arrays look a lot like information about a Person (with the name and some value, maybe a score).
What you'd want to do is to write a custom class to hold that information:
public class Person {
private final String name;
private final double score;
public Person(final String name, final double score) {
this.name=name;
this.score=score;
}
public String getName() {
return name;
}
public double getScore() {
return score;
}
}
Then, when you want to sort them, you simply implement a Comparator<Person> that specifies how you want them sorted:
public PersonScoreComparator implements Comparator<Person> {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getScore(), p2.getScore());
}
}
Alternatively, you could have the Person class itself implement Comparable<Person> by adding this method:
public int compareTo(Person other) {
return Double.compare(getScore(), other.getScore());
}
-Create list out of this array using Arrays.toList()
-Design comparator using java.lang.comparator and write logic for sorting every even elements
There are several sort methods in java.util.Arrays. Two of them take custom Comparators. Simply provide a comparator comparing the second element of the inner arrays.
public static void main(String[] args)
{
String Name[][]={{"prakash","kumar"},{"raj","kappor"},{"vinod","bhart"}};
String str[]=new String[2];
for(int j=0; j<Name.length;j++)
{
for (int i=0 ; i<2; i++)
{
str[i]=Name[j][i];
}
for(int i=0;i<str.length;i++)
{
for(int k=i+1;k<str.length;k++)
{
if(str[i].compareTo(str[k])>0)
{
String temp= str[i];
str[i]=str[k];
str[k]=temp;
}
}
System.out.print(str[i]+ " ");
}
System.out.println();
}
}
}
/**
*
* #param array - 2D array required to be arranged by certain column
* #param columnIndex - starts from 0; this will be the main comparator
* #param hasHeaders - true/false; true - ignore the first row. False -
* first row it's also compared and arranged
* #return - the new arranged array
*/
private String[][] arrangeArray(String[][] array, int columnIndex, boolean hasHeaders) {
int headersExists = 0;
if (hasHeaders) {
headersExists = 1;
}
for (int i = headersExists; i < array.length; i++) {
for (int j = headersExists; j < array.length; j++) {
if (array[i][columnIndex].compareTo(array[j][columnIndex]) < 0){
String[] temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}

Sorting a List of LIst by the Value of the sublist

private List<String> subList;
private List<List<String>> records = new ArrayList<List<String>>();
for(....){
subList = new ArrayList<String>();
...populate..
records.add(subList);
}
For example, subList has three Strings - a, b, and c.
I want to sort the records by the value of b in subList.
records at 0 has a list of "10", "20", "30"
records at 1 has a list of "10", "05", "30"
records at 2 has a list of "10", "35", "30"
After the sort, the order of records should be -
records at 0 = records at 1 above
records at 1 = records at 0 above
records at 2 = records at 2 above
What could be a good algorithm for that?
Something like:
Collections.sort(records, new Comparator<List<String>>()
{
public int compare(List<String> o1, List<String> o2)
{
//Simple string comparison here, add more sophisticated logic if needed.
return o1.get(1).compareTo(o2.get(1));
}
})
Though I find hard-coding the positions a little dubious in practice, your opinion may differ.
This is just like sorting a string of characters: given two strings, start at the beginning and compare each character; if there's a difference, the string with the lower value comes first, otherwise, look at the next characters from each string. If the strings are of different lengths, treat the shorter string as if it had a suffix of zeroes.
In this case, the "characters" are integer values, obtained by calling Integer.parseInt(). Additionally, implementing a Comparator for a List<String> would be helpful here. Then the Collections.sort() method can be used.
The comparator might look something like this:
final class MyComparator implements Comparator<List<String>> {
public int compare(List<String> a, List<String> b) {
/* Assume all strings are parseable to values
* in range [0,Integer.MAX_VALUE] */
int len = Math.min(a.size(), b.size());
for (int idx = 0; idx < len; ++idx) {
int va = Integer.parseInt(a.get(idx)), vb = Integer.parseInt(b.get(idx));
if (va != vb)
return va - vb;
}
return va.size() - vb.size();
}
#Override
public boolean equals(Object o) {
return o instanceof MyComparator;
}
#Override
public int hashCode() {
return MyComparator.class.hashCode();
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MyList
{
private List<List<Long>> myList;
public MyList()
{
myList = new ArrayList<List<Long>>();
ArrayList arrayList = null;
for(int i=0;i<3;i++)
{
arrayList = new ArrayList<Long>();
for(int x=0;x<3;x++)
{
arrayList.add((Long)Math.round(Math.random()*10));
}
myList.add(arrayList);
}
}
public static void main(String[] args)
{
MyList newList = new MyList();
newList.printList();
Collections.sort(newList.getMyList(),new Comparator<List<Long>>(){
public int compare(List<Long> o1, List<Long> o2) {
if(o1 != null && o2 !=null)
{
Long var1 = o1.get(0);
Long var2 = o2.get(0);
return var1.compareTo(var2);
}
return 0;
}
});
newList.printList();
}
private void printList() {
for(List<Long> subString : myList)
{
System.out.println("List");
for(Long elements : subString)
{
System.out.println(elements);
}
}
}
public List<List<Long>> getMyList() {
return myList;
}
public void setMyList(List<List<Long>> myList) {
this.myList = myList;
}
}
The Column Comparator allows your to sort on any column within the List. The sort is done using the natural sort order of the data in the column.

Categories

Resources