Created
February 26, 2014 22:27
-
-
Save CalebWhiting/9240024 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package edu.revtek.util; | |
| import java.lang.reflect.*; | |
| import java.util.*; | |
| /** | |
| * @author Caleb Whiting | |
| */ | |
| public class CompareTest { | |
| public static void main(String[] args) { | |
| Random random = new Random(); | |
| List<Wrapper> wrappers = new LinkedList<>(); | |
| for (int i = 0; i < 10; i++) { | |
| wrappers.add(new Wrapper(random.nextInt(50))); | |
| } | |
| printWrappers(wrappers, "Unsorted"); | |
| // Compare Properties | |
| Collections.sort(wrappers, new PropertyComparator<Wrapper>(Method.class, "getValue")); | |
| // Compare Normally | |
| Collections.sort(wrappers, new Comparator<Wrapper>() { | |
| @Override | |
| public int compare(Wrapper o1, Wrapper o2) { | |
| return Integer.compare(o1.getValue(), o2.getValue()); | |
| } | |
| }); | |
| printWrappers(wrappers, "Sorted"); | |
| } | |
| static void printWrappers(Collection<Wrapper> wrappers, String message) { | |
| System.out.println(message); | |
| for (Wrapper wrapper : wrappers) { | |
| System.out.print(' '); | |
| System.out.println(wrapper.value); | |
| } | |
| } | |
| static class Wrapper { | |
| private final int value; | |
| public Wrapper(int value) { | |
| this.value = value; | |
| } | |
| public int getValue() { | |
| return value; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment