Created
February 17, 2017 15:21
-
-
Save 13andrew13/89aaf8a98f3ac7fd747bda30e8ee1a59 to your computer and use it in GitHub Desktop.
This file contains 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 compare.NamesComparing; | |
import java.util.*; | |
/** | |
* Created by andrew on 17.02.17. | |
*/ | |
public class Names { | |
private List<String> names = new ArrayList<>(); | |
public Names() { | |
} | |
public Names addName(String o){ | |
names.add(o); | |
return this; | |
} | |
public void sortAlphabet (){ | |
Collections.sort(names); | |
} | |
public void sortReversed(){ | |
Collections.sort(names, Comparator.reverseOrder()); | |
} | |
public String leastName(){ | |
return Collections.min(names); | |
} | |
public void sortNamesLength(){ | |
Collections.sort(names, new Comparator<String>() { | |
@Override | |
public int compare(String o1, String o2) { | |
int s1 = o1.length(); | |
int s2 = o2.length(); | |
return s1 - s2; | |
} | |
}); | |
} | |
public void sortByLengthExtended(){ | |
Collections.sort(names, new Comparator<String>() { | |
@Override | |
public int compare(String o1, String o2) { | |
int s1 = o1.length(); | |
int s2 = o2.length(); | |
if(s1!=s2){ | |
return s1 -s2; | |
} | |
else | |
return 0- o1.compareTo(o2); | |
} | |
}); | |
} | |
@Override | |
public String toString() { | |
return "Names{" + names + | |
'}'; | |
} | |
} | |
This file contains 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 compare.NamesComparing; | |
/** | |
* Created by andrew on 17.02.17. | |
*/ | |
public class NamesRunner { | |
public static void main(String[] args) { | |
Names names = new Names(); | |
names.addName("Bob").addName("Josh").addName("Michel").addName("Antony"); | |
System.out.println(names); | |
names.sortAlphabet(); | |
System.out.println(names); | |
names.sortReversed(); | |
System.out.println(names); | |
System.out.println(names.leastName()); | |
names.sortNamesLength(); | |
System.out.println(names); | |
names.sortByLengthExtended(); | |
System.out.println(names); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment