Problem statement: Given the collection of StringBuffer objects.
StringBuffer sb1 = new StringBuffer("Z");
StringBuffer sb2 = new StringBuffer("A");
StringBuffer sb3 = new StringBuffer("P");
You have to sort it either way, meaning natural order or custom order.
Answer:
// ASCENDING ORDER:
StringBuffer sb1 = new StringBuffer("Z");
StringBuffer sb2 = new StringBuffer("A");
StringBuffer sb3 = new StringBuffer("P");
You have to sort it either way, meaning natural order or custom order.
Answer:
// ASCENDING ORDER:
- import java.util.Comparator;
- import java.util.TreeSet;
- public class Test {
- public static void main(String[] args) {
- SortStringBufferObject s = new SortStringBufferObject();
- TreeSet<StringBuffer> t = new TreeSet<>(s);
- t.add(new StringBuffer("Z"));
- t.add(new StringBuffer("A"));
- t.add(new StringBuffer("P"));
- System.out.println(t);
- }
- }
- class SortStringBufferObject implements Comparator<StringBuffer> {
- public int compare(StringBuffer sb1, StringBuffer sb2) {
- return sb1.toString().compareTo(sb2.toString());
- }
- }
Output:
[A, P, Z]
// DESCENDING ORDER:
- import java.util.Comparator;
- import java.util.TreeSet;
- public class Test {
- public static void main(String[] args) {
- SortStringBufferObject s = new SortStringBufferObject();
- TreeSet<StringBuffer> t = new TreeSet<>(s);
- t.add(new StringBuffer("Z"));
- t.add(new StringBuffer("A"));
- t.add(new StringBuffer("P"));
- System.out.println(t);
- }
- }
- class SortStringBufferObject implements Comparator<StringBuffer> {
- public int compare(StringBuffer sb1, StringBuffer sb2) {
- return sb2.toString().compareTo(sb1.toString());
- }
- }
Output:
No comments:
Post a Comment