Sunday, 22 July 2012

String Display in ascending and descending using comparator interface in java

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

Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...