java单词排序,根据Java中的字符列表对单词列表进行排序

I have:

List alphabet; (contains 26 unique characters as elements, for example

qwertyuiosapdfghjklzcxvbnm)

List wordsToArrange; contains words as elements, for example:

- apple

- stream

- posthouse

- sea

- seed

I need to arrange the words according to the alphabet i have made.

My approach at the moment is with for cycles.

alphabet(i) compare it with all the words charAt(0)

if only 1 is found i put it to a new list arrangedList

but if 2 is found i go alphabet(i+1) till the letter is found and now i can put them in a right order to arrangedList....

then move back to alphabet(i+1) till alphabet(26) and now all should be arranged correctly...

I have wrote some base for this code but i wanted to ask what would be other approaches before i start the serious "for cyclying".

Thanks!

解决方案

What about wrapping the String in a new Class that implements comparable?

May be some edge case bugs that i have not tested.

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class CompString {

public static void main(String[] args) {

List list = new ArrayList();

list.add(new ComparableString("apple"));

list.add(new ComparableString("stream"));

list.add(new ComparableString("posthouse"));

list.add(new ComparableString("sea"));

list.add(new ComparableString("seed"));

Collections.sort(list);

System.out.println(list);

}

}

class ComparableString implements Comparable {

String str;

static String sortOrder = "qwertyuiosapdfghjklzcxvbnm";

public ComparableString(String string) {

str = string;

}

@Override

public String toString() {

return str;

}

@Override

public int compareTo(ComparableString other) {

for (int i = 0; i < Math.min(this.str.length(), other.str.length()); i++) {

int thisOrder = ComparableString.sortOrder.indexOf(this.str.charAt(i));

int thatOrder = ComparableString.sortOrder.indexOf(other.str.charAt(i));

int order = thisOrder - thatOrder;

if (order != 0) {

return order;

}

}

if (this.str.length() > other.str.length()) {

return -1;

} else if (this.str.length() < other.str.length()) {

return 1;

}

return 0;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值