Using Comparator to sort the arraylist.
package CollectionFramework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class ComparatorAndComparable {
public static void main(String[] args) {
// TODO Auto-generated method stub
new Fruits().listOfFruits();
}
}
// example to show the use of comparator and comparable
// Use of comparator example. Sorting String Objecy
class Fruits {
public void listOfFruits() {
List<String> fruits = new ArrayList<String>();
// this is am array list which accepts String type object
// let us have some fruits
String s1 = "grapes";
String s2 = "Gooseberries";
String s3 = "Apple";
String s4 = "Zfruit";
String s5 = "zafruit";
// add these fruits to the arrayList
fruits.add(s1);
fruits.add(s2);
fruits.add(s3);
fruits.add(s4);
fruits.add(s5);
// Collections.sort(fruits); // this will only work if all the fruit
// starts with same case
Collections.sort(fruits, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return o1.compareToIgnoreCase(o2);
}
});
Iterator<String> it = fruits.iterator();
while (it.hasNext()) {
String value = it.next();
System.out.println(value);
}
}
}
Using Comparable to sort arraylist
package CollectionFramework;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class ComparatorAndComparable {
public static void main(String[] args) {
new fruitArrayList().fruitArray();
}
}
// when we are comparing any object then use comparable
class FruitsName implements Comparable<FruitsName> {
String name;
public void fruitName(String name) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(FruitsName o) {
// TODO Auto-generated method stub
return this.name.compareToIgnoreCase(o.getName());
}
}
class fruitArrayList {
public void fruitArray() {
List<FruitsName> fruitnameArray = new ArrayList<>();
// create a fruit Object
FruitsName orange = new FruitsName();
orange.setName("Orange");
FruitsName apple = new FruitsName();
apple.setName("apple");
FruitsName grapes = new FruitsName();
grapes.setName("Grapes");
fruitnameArray.add(orange);
fruitnameArray.add(apple);
fruitnameArray.add(grapes);
Collections.sort(fruitnameArray);
Iterator<FruitsName> itr = fruitnameArray.iterator();
while (itr.hasNext()) {
System.out.println(itr.next().getName());
}
}
}
No comments:
Post a Comment