《面试题》产生20个不同的随机数,并降序排列 发表于 2017-09-03 | 分类于 面试题 | | 浏览 次 随机生成20个不重复的小写字母并进行排序,排序方式为倒序。 题目描述随机生成20个不重复的小写字母并进行排序,排序方式为倒序。 解决方案12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import java.util.Collections;import java.util.Set;import java.util.List;import java.util.HashSet;import java.util.ArrayList;import java.util.Iterator;import java.util.Comparator;/** * @author: Cecurio * @create: 2017-09-03 17:22 * @desc: **//*随机生成20个不重复的小写字母并进行排序,排序方式为倒序。 */public class Demo { private Set<Character> chars; private List<Character> list; public void generate(){ chars = new HashSet<Character>(); list = new ArrayList<Character>(); while (chars.size() < 20) { char tmp = (char)((int)(Math.random()*26) + 97); chars.add(tmp); } Iterator<Character> it = chars.iterator(); while (it.hasNext()) { list.add(it.next()); } } public void descSort(){ Collections.sort(list, new Comparator<Character>() { public int compare(Character o1, Character o2) { return o2.compareTo(o1); } }); } public void print() { int i = 0; for (Character character : list) { i++; System.out.println("" + i + " -> " + character); } } public static void main(String[] args) { Demo demo = new Demo(); demo.generate(); demo.descSort(); demo.print(); }} If you think the content is useful to you. 赏 微信打赏 支付宝打赏