Collecrions.Sort using user defined method
Problem : Here we are going to sort a STL (Arraylist) by Collections.sort() method but comparison will be done by our method.
Collections.sort(arr,(a,b) ->
{
return (b+a).compareTo(a+b);
});
It will take arraylist arr as parameter and change whether string b+a is less than to string a+b or not and will sort accordingly.
In other method we can create a class which implements comparator and a function compare will be overriden and it will pe passed as -> Collections.sort(arr,new sortbyroll())
Example in the given code here it will form maximum number using numbers in an array
Ex: 9 98 45 93 7
Output: 99893745
import java.util.*;
import java.lang.*;
import java.io.*;
class Sortbyroll implements Comparator<String>
{
// Used for sorting in ascending order of
// roll number
@Override
public int compare(String a, String b)
{
return (b+a).compareTo(a+b);
}
}
class sortbycompare
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
ArrayList<String> arr=new ArrayList<String>();
// add data into arraylist for n numbers
while(n-->0)
{
arr.add(ab.next());
}
Collections.sort(arr,(a,b) ->
{
return (b+a).compareTo(a+b);
});
}
}
}}
Collections.sort(arr,(a,b) ->
{
return (b+a).compareTo(a+b);
});
It will take arraylist arr as parameter and change whether string b+a is less than to string a+b or not and will sort accordingly.
In other method we can create a class which implements comparator and a function compare will be overriden and it will pe passed as -> Collections.sort(arr,new sortbyroll())
Example in the given code here it will form maximum number using numbers in an array
Ex: 9 98 45 93 7
Output: 99893745
import java.util.*;
import java.lang.*;
import java.io.*;
class Sortbyroll implements Comparator<String>
{
// Used for sorting in ascending order of
// roll number
@Override
public int compare(String a, String b)
{
return (b+a).compareTo(a+b);
}
}
class sortbycompare
{
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
ArrayList<String> arr=new ArrayList<String>();
// add data into arraylist for n numbers
while(n-->0)
{
arr.add(ab.next());
}
Collections.sort(arr,(a,b) ->
{
return (b+a).compareTo(a+b);
});
}
}
}}
0 Comments:
Post a Comment