|
| 1 | +package org.baeldung.java.sorting; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | + |
| 5 | +import java.sql.Array; |
| 6 | +import java.util.Arrays; |
| 7 | +import java.util.Collections; |
| 8 | +import java.util.Comparator; |
| 9 | +import java.util.List; |
| 10 | + |
| 11 | +import org.junit.Before; |
| 12 | +import org.junit.Test; |
| 13 | + |
| 14 | +public class ArraySort { |
| 15 | + |
| 16 | + private int[] numbers; |
| 17 | + private Integer[] integers; |
| 18 | + private String[] names; |
| 19 | + private Employee[] employees; |
| 20 | + |
| 21 | + @Before |
| 22 | + public void initData() { |
| 23 | + numbers = new int[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; |
| 24 | + integers = new Integer[] { 5, 1, 89, 255, 7, 88, 200, 123, 66 }; |
| 25 | + |
| 26 | + names = new String[] { "John", "Apple", "Steve", "Frank", "Earl", "Jessica", "Jake", "Pearl" }; |
| 27 | + |
| 28 | + employees = new Employee[] { new Employee("John", 23, 5000), new Employee("Steve", 26, 6000), new Employee("Frank", 33, 7000), |
| 29 | + new Employee("Earl", 43, 10000), new Employee("Jessica", 23, 4000), new Employee("Pearl", 33, 6000) }; |
| 30 | + |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void naturalSortIntArray() { |
| 35 | + |
| 36 | + Arrays.sort(numbers); |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void comparatorSortIntArray() { |
| 42 | + |
| 43 | + Arrays.sort(integers, new Comparator<Integer>() { |
| 44 | + |
| 45 | + @Override |
| 46 | + public int compare(Integer a, Integer b) { |
| 47 | + return a - b; |
| 48 | + } |
| 49 | + }); |
| 50 | + |
| 51 | + } |
| 52 | + |
| 53 | + @Test |
| 54 | + public void comparatorSortIntArray_Java8Lambda() { |
| 55 | + Arrays.sort(integers, (a, b) -> { |
| 56 | + return a - b; |
| 57 | + }); |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + @Test |
| 62 | + public void comparableSortEmployeeArrayByAge_NaturalOrder() { |
| 63 | + |
| 64 | + Arrays.sort(employees); |
| 65 | + |
| 66 | + } |
| 67 | + |
| 68 | + @Test |
| 69 | + public void comparatorSortEmployeeArrayByName() { |
| 70 | + Arrays.sort(employees, new Comparator<Employee>() { |
| 71 | + |
| 72 | + @Override |
| 73 | + public int compare(Employee o1, Employee o2) { |
| 74 | + |
| 75 | + return o1.getName().compareTo(o2.getName()); |
| 76 | + } |
| 77 | + }); |
| 78 | + } |
| 79 | + |
| 80 | + @Test |
| 81 | + public void comparatorSortEmployeeArrayByName_Java8Lambda() { |
| 82 | + Arrays.sort(employees, (o1, o2) -> { |
| 83 | + return o1.getName().compareTo(o2.getName()); |
| 84 | + |
| 85 | + }); |
| 86 | + } |
| 87 | + |
| 88 | +} |
0 commit comments