String Display in ascending and descending using comparator interface in java
package com.demo;
import java.util.Arrays;
import java.util.Comparator;
public class StringOperations {
public static void main(String[] args) {
String[] names = {"Chenni", "Mumbai", "Delhi","Agra","Andhra","Patna"};
// Ascending
System.out.println("Ascending");
System.out.println("---------");
Arrays.sort(names);
displayLoop(names);
// Descending
System.out.println("Descending");
System.out.println("----------");
Comparator<String> descending = new DescendingComparator();
Arrays.sort(names,descending);
displayLoop(names);
}
private static void displayLoop(String[] names) {
for(String namedisplay:names)
{
System.out.println(""+namedisplay);
}
}
}
Class DescendingComparator
package com.demo;
import java.util.Comparator;
public class DescendingComparator implements Comparator<String> {
@Override
public int compare(String str1, String str2) {
// TODO Auto-generated method stub
return str2.compareTo(str1);
// return str1.compareTo(str2);
// return str1.concat(str2);
}
}
No comments:
Post a Comment