为什么当我删除toLowerCase()然后不对我的单词进行排序?

时间:2015-03-11 20:51:27

标签: java

为什么当我删除toLowerCase()然后不对我的单词进行排序? 我怎么解决这个问题?我不会在我的xml中小写和大案例吗? 这是Java 8

我的所有代码

class Word implements Comparable<Word>{
    private final String word;

    Word(String word) {
        this.word = word;
    }

    @Override
    public int compareTo(Word o) {
        return word.compareTo(o.word);
    }

    @Override
    public String toString() {
        return word;
    }
}

class Sentence {
    private final List<Word> words;

    Sentence(List<Word> words) {
        Collections.sort(words);
        this.words = words;
    }

    public List<Word> getWords(){
        return words;
    }
}

interface Converter{
    String convert(Sentence sentence);
}



class CSVConverter implements Converter{

    @Override
    public String convert(Sentence sentence){
        return sentence.getWords().stream().map(Object::toString).collect(Collectors.joining(","))+"\n";
    }
}


//XML Converter
class XMLConverter implements Converter{

    @Override
    public String convert(Sentence sentence){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<sentence>\n");
        for(Word word : sentence.getWords()){
            stringBuilder.append("\t<word>");
            stringBuilder.append(word);
            stringBuilder.append("</word>\n");
        }
        stringBuilder.append("</sentence>\n");
        return stringBuilder.toString();
    }
}


//main class whit function to edit text writ whit Java 8
public class Nordea {
    public static void main(String[] args) throws IOException {
        Pattern unicodeWord = Pattern.compile("\\w+", Pattern.UNICODE_CHARACTER_CLASS);
        Converter converter = new CSVConverter();
        converter = new XMLConverter();

        Files.lines(Paths.get("text.txt"))
                .map(line -> line.toLowerCase().replaceAll("\\s+", " "))
                .flatMap(line -> Arrays.stream(line.split("[\\.!?]")))
                .map(sentence -> Arrays.stream(sentence.split(" "))
                                .filter(word -> unicodeWord.matcher(word).matches())
                                .map(Word::new)
                                .collect(Collectors.toList())
                )
                .filter(list -> list.size()>0)
                .map(Sentence::new)
                .map(converter::convert)
                .forEach(System.out::print);

        System.out.println();
    }
}

为什么当我删除toLowerCase()然后不对我的单词进行排序? 我怎么解决这个问题?我不会在我的xml中小写和大案例吗? 这是Java 8 这是Java 8

2 个答案:

答案 0 :(得分:1)

最好在比较之前实现一个降低文本范围的比较器。

在我看来,这比在Word对象的compareTo方法中做的更好,除非你认为小写比较是Word的“自然”排序的默认值。

答案 1 :(得分:0)

尝试这应该可行

@Override
public int compareTo(Word o) {
    String thisStr= this.word.toLower();
    String oStr=o.word.toLower();
    return thisStr.compareTo(oStr);
}