Sorting PriorityQueue - java

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;
}
}

Related

how do i sort this custom arraylist in java , in descending order of the number of boxes packed

this is my first class for the Crackerpacker,i have created another class for the arraylist and then added all these cracker packers to that arraylist , now i want to sort the arraylist in descending order of number of boxes packed by the CrackerPackers
public class CrackerPacker {
private String name;
private int numberOfBoxes;
public CrackerPacker (String name, int numberOfBoxes){
this.name = name;
this.numberOfBoxes = numberOfBoxes;
}
public int getNumberOfBoxes() {
return numberOfBoxes;
}
public void setNumberOfBoxes(int numberOfBoxes) {
this.numberOfBoxes = numberOfBoxes;
}
public String getName() {
return name;
enter code here
}
#Override
public String toString() {
return "CrackerPacker{" +
"name='" + name + '\'' +
", numberOfBoxes=" + numberOfBoxes +
'}';
}
public double getwage() {
if ( numberOfBoxes < 51 ) {
return numberOfBoxes * 1.15;
}
else {
double wage = (57.5 + ((numberOfBoxes - 50) * 1.25));
return wage;
This is the second class in which i have created an arraylist to add all the crackerpacker objects in it
this arraylist i want sort in descending order of the number of boxes packed by the CrackerPackers
import java.util.ArrayList;
import java.util.Collections;
public class Common {
public static ArrayList<CrackerPacker> lectures = new ArrayList<>();
int sum = 0;
int boxes = 0;
public int totalWage() {
for (int i = 0; i < lectures.size(); i++) {
sum += lectures.get(i).getwage();
}
return sum;
}
public int totalBoxes() {
for (int i = 0; i < lectures.size(); i++){
boxes += lectures.get(i).getNumberOfBoxes();
}
return boxes;
This my main method , i want sort the array list in descending roder of the number of boxes packed by the objects , please show me how can do it
import java.util.Collections;
public class Main {
public static void main(String[] args) {
CrackerPacker steve = new CrackerPacker("STEVE", 127);
CrackerPacker gary = new CrackerPacker("Gary", 103);
CrackerPacker tony = new CrackerPacker("tony", 473);
CrackerPacker saad = new CrackerPacker("Saad", 129);
CrackerPacker rubiya = new CrackerPacker("rubiya", 117);
Common common = new Common();
Common.lectures.add(steve);
Common.lectures.add(gary);
Common.lectures.add(tony);
Common.lectures.add(saad);
Common.lectures.add(rubiya);
for ( CrackerPacker element : Common.lectures) {
System.out.println(element);
}
System.out.println(common.totalWage());
System.out.println(common.totalBoxes());
i think i have use the compareto method but i dont knwo how to implement it
The below compares the numberOfBoxes of the passed CrackerPacker with that of the current objects. This will have the effect of sorting it in descending order.
public class CrackerPacker implements Comparable<CrackerPacker> {
#Override
public int compareTo(CrackerPacker c) {
return Integer.compare(c.numberOfBoxes, this.numberOfBoxes);
}
}
From the javadoc,
Compares this object with the specified object for order. Returns a
negative integer, zero, or a positive integer as this object is less
than, equal to, or greater than the specified object.
Hence, when comparing two CrackerPacker objects we are reversing the Integer compare check to achieve a descending ordering.
Example: Comparing 5 and 10, we are comparing 10 with 5 and hence Integer.compare returns 1 (since 10 > 5). But from outside comparison, we are stating that the first object is bigger than the second and hence it will appear after the second (..10....5...). This sorts the list in descending order.
The following expression will help
Collections.sort(Common.lectures, (Comparator< CrackerPacker >) (o1, o2) -> Integer.compare(o1.getNumberOfBoxes(), o2.getNumberOfBoxes()));

Method for adding Objects into a fixed collection(Array) in Java

I have made an inheritance hierarchy with one super-class called Employe and two subclasses called Lecturer and Assistant. In addition to this I made a class called Subject which has an array of employees.
What I want to do here is create a method for adding Employe objects into the array.
I made the same one that works for ArrayList, but it didn't seem to work for Arrays.
If it is possible, how can I create a method for doing the same thing with arrays?
public class Subject {
private String subjectcode;
private Employe[] employees;
public Subject(String subjectcode) {
this.subjectcode = subjectcode;
Employe[] employees = new Employe[5];
}
public void setSubjectcode(String code) {
this.subjectcode = code;
}
public String getSubjectcode() {
return this.subjectcode;
}
public boolean addStaff(Employe employe) {
if (employe instanceof Lecturer || employe instanceof Assistant) {
this.employees.add(employe);
return true;
} else {
return false;
}
}
}
You need to use an ArrayList :
public class Subject
{
private String subjectcode;
private final List<Employee> employees = new ArrayList<Employee>();
public Subject(String subjectcode){
this.subjectcode = subjectcode;
}
public boolean addStaff(Employe employe){
return this.employees.add(employe);
}
Or if you still want to use an array :
public boolean addStaff(Employe employe){
List<Employee> tempList = Arrays.asList(this.employees);
boolean added = tempList.add(employe);
this.employees = tempList.toArray(this.employees);
return added;
}
Arrays cannot grow or shrink dynamically by themselves as ArrayLists do, that's why the don't have add() method — it'd stop working after array instance is full.
What you have with arrays are, essentially, a get(index) and set(index, value), so when you know that you will have at maximum N employees, Subject may look like this:
public class Subject {
private static final int N = 5;
private String subjectcode;
private Employe[] employees = new Employe[N];
private int size = 0;
public Subject(String subjectcode){
this.subjectcode = subjectcode;
}
public void setSubjectcode(String code){
this.subjectcode = code;
}
public String getSubjectcode(){
return this.subjectcode;
}
public boolean addStaff(Employe employe){
if (size == employees.length) {
// cannot add when is full
return false;
}
if(employe instanceof Lecturer || employe instanceof Assistant){
this.employees[size++] = employe;
return true;
}
return false;
}
}
On the other hand, if you don't know how many employees Subject may have even at a time when Subject is created (if you'd know it, you may pass N as a constructor argument), you'd have to implement method for growing internal array and call it whenever new employe is added, which may look like this:
private void ensureCapacity(int n) {
int oldCapacity = employees.length;
if (oldCapacity >= n) {
// there's nothing to do
return;
}
// grow at least in half, to minimize copying data on each add
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - n < 0)
newCapacity = n;
employees = Arrays.copyOf(employees, newCapacity);
}
public boolean addStaff(Employe employe) {
ensureCapacity(size + 1);
if (employe instanceof Lecturer || employe instanceof Assistant) {
this.employees[size++] = employe;
return true;
}
return false;
}
For better example of growing arrays see default implementation of ArrayList's ensureCapacity(int minCapacity) in JDK.
But again, this growing-shrinking stuff is just reimplementing what is done already in ArrayList for you.
In case of Java arrays, unlike ArrayList you do not have add method. So, you cannot add like it. Array operates as below:
String[] employees = new String[5];
employees[0] = "ad";
So, array needs index based approach, where you specify that at index 0 put this element, at index 1 put this element, and so on .... employees[0] = "as";
In your case, why you need to use array? I think ArrayList fits best, as per information you have provided.

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.

java: TreeSet order

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.

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;
}

Categories

Resources