java中怎样把输入的基本英文单词按首字母顺序排列?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java中怎样把输入的基本英文单词按首字母顺序排列?相关的知识,希望对你有一定的参考价值。
import java.util.ArrayList;import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* 规则:大写字母前于小写字母
*
* @author Administrator
*
*/
public class SortWords
private static final String[] array = "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z" ;
public static void main(String[] args)
SortWords sw = new SortWords();
List<String> words = new ArrayList<String>();
words.add("book");
words.add("ear");
words.add("alert");
words.add("choice");
words.add("name");
words.add("memery");
words.add("fight");
words.add("call");
words.add("joy");
List<String> list = sw.sort(words, "forward");
for (String str : list)
System.out.println(str);
public List<String> sort(List<String> words, String type)
List<Word> list = new ArrayList<Word>();
List<String> res = new ArrayList<String>();
for (String word : words)
Word w = indexNum(word);
list.add(w);
switch (type)
case "forward":
Collections.sort(list, new Forward());
for (Word w : list)
res.add(w.getContent());
break;
case "back":
Collections.sort(list, new Back());
for (Word w : list)
res.add(w.getContent());
break;
return res;
public Word indexNum(String word)
String[] letters = word.split("");
String res = "";
Word w = new Word();
String letter = word.substring(0, 1);
for (int i = 0; i < array.length; i++)
String pattern = array[i];
if (letter.equalsIgnoreCase(pattern))
res += i;
break;
w.setContent(word);
w.setIndexNum(Integer.parseInt(res));
return w;
private class Forward implements Comparator
@Override
public int compare(Object arg0, Object arg1)
Word w1 = (Word) arg0;
Word w2 = (Word) arg1;
int flag = w1.getIndexNum() - w2.getIndexNum();
return flag;
private class Back implements Comparator
@Override
public int compare(Object arg0, Object arg1)
Word w1 = (Word) arg1;
Word w2 = (Word) arg0;
int flag = w1.getIndexNum() - w2.getIndexNum();
return flag;
class Word
private String content;
private Integer indexNum;
public String getContent()
return content;
public void setContent(String content)
this.content = content;
public Integer getIndexNum()
return indexNum;
public void setIndexNum(Integer indexNum)
this.indexNum = indexNum;
参考技术A 用list集合试试。list集合是里放的是有顺序并且重复的东西。。 参考技术B java中把排序查找等一系列算法都封装再一个叫collections的类里面有了,所以你把输入的字母存在数组或其他集合中,然后直接一句collections.sort();就排好了,你参考javaAPI中对这个类的详解会更吃惊的,呵呵呵 参考技术C ASC码是按字母序的 所以你可以用asc码来排序
以上是关于java中怎样把输入的基本英文单词按首字母顺序排列?的主要内容,如果未能解决你的问题,请参考以下文章