fork download
  1. import java.util.Arrays;
  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.List;
  5.  
  6. class Item {
  7. private String name;
  8.  
  9. public Item() {
  10. super();
  11. }
  12.  
  13. public Item(final String name) {
  14. super();
  15. this.name = name;
  16. }
  17.  
  18. public String getName() {
  19. return name;
  20. }
  21.  
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25.  
  26. @Override
  27. public String toString() {
  28. return String.format("Item[name=%s]", getName());
  29. }
  30. }
  31.  
  32. class ItemTest {
  33. public static void main(final String[] args) {
  34. try {
  35. testSortItemArrByNameExcludingThe();
  36. testSortItemListByNameExcludingThe();
  37. } catch (final Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41.  
  42. public static void testSortItemArrByNameExcludingThe() throws Exception {
  43. final Item[] itemArr = new Item[] { new Item("The Abacus"),
  44. new Item("The Killing of Molly Brown"),
  45. new Item("The What and The Who"),
  46. new Item("The Fighting Temptations"),
  47. new Item("Doctor Seusses Cat in the Hat") };
  48.  
  49. Arrays.sort(itemArr, new Comparator<Item>() {
  50. public int compare(Item a, Item b) {
  51. String newA = a.getName().replaceAll("(?i)^the\\s+", "");
  52. String newB = b.getName().replaceAll("(?i)^the\\s+", "");
  53. return newA.compareToIgnoreCase(newB);
  54. }
  55. });
  56.  
  57. System.out.println("Array Sort:" + Arrays.toString(itemArr));
  58. }
  59.  
  60. public static void testSortItemListByNameExcludingThe() throws Exception {
  61. final Item[] itemArr = new Item[] { new Item("The Abacus"),
  62. new Item("The Killing of Molly Brown"),
  63. new Item("The What and The Who"),
  64. new Item("The Fighting Temptations"),
  65. new Item("Doctor Seusses Cat in the Hat") };
  66.  
  67. final List<Item> itemList = Arrays.asList(itemArr);
  68. Collections.sort(itemList, new Comparator<Item>() {
  69. public int compare(Item a, Item b) {
  70. String newA = a.getName().replaceAll("(?i)^the\\s+", "");
  71. String newB = b.getName().replaceAll("(?i)^the\\s+", "");
  72. return newA.compareToIgnoreCase(newB);
  73. }
  74. });
  75.  
  76. System.out.println("Lists Sort:" + itemList);
  77. }
  78. }
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
Array Sort:[Item[name=The Abacus], Item[name=Doctor Seusses Cat in the Hat], Item[name=The Fighting Temptations], Item[name=The Killing of Molly Brown], Item[name=The What and The Who]]
Lists Sort:[Item[name=The Abacus], Item[name=Doctor Seusses Cat in the Hat], Item[name=The Fighting Temptations], Item[name=The Killing of Molly Brown], Item[name=The What and The Who]]