繁体   English   中英

如何按对象 state 降序对充满对象的集合进行排序?

[英]How to sort a collection filled with objects in a descending order by objects state?

输入是:

  • asd 43 asdf asd 43

  • 第434章

  • kasdf asdf 停止 asdf

  • 停止

output 应该是:

  • 非洲自卫队:4

  • 43:2

  • 时差:2

  • 434:1

  • 卡斯达夫:1

  • 停止:1

在一行“停止”它应该停止

我有这个 class:

public class Word implements Comparable<Word> {

    private String content;
    private int frequency;

    public Word(String content) {
        this.content = content;
        this.frequency = 1;
    }

    @Override
    public int compareTo(Word o) {
        return this.frequency - o.frequency;

    }

    @Override
    public String toString() {
        return "" + content  + " : " + frequency;
    }
}

第二个 class Wordcontainer 应具有所有功能:

public class WordContainer {
    static List<Word> list = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = null;


        Pattern p = Pattern.compile("\\S+");

        while (!(line = reader.readLine()).equals("stop")) {
            Matcher m = p.matcher(line);
            while (m.find()) {
                addon(new Word(m.group()));
            
            }
        }

        public static void addon(Word word) {
            for (Word w : list) {
                if (w.getContent().equals(word.getContent())) {
                    w.setFrequency(w.getFrequency() + 1);
            }
        }
        list.add(word);
    }
}

我如何用对象 new Word 填充此列表,以便频率按降序排列? 现在我明白了

  • 非洲自卫队:4

  • 非洲自卫队:3

  • 43:2

  • 时差:2

  • 非洲自卫队:2

  • 43:1

  • 434:1

  • asd:1

  • 非洲自卫队:1

  • 卡斯达夫:1

  • 停止:1

这是你代码中的一个错误,可以通过修改addon方法来修复。

public static void addon(Word word) {
    list.stream()
        .filter(w -> w.getContent().equals(word.getContent()))
        .findFirst()
        .ifPresentOrElse(w -> w.setFrequency(w.getFrequency()+1), () -> list.add(word));
}

您将单词添加到列表中,即使频率匹配/增加也是如此。

Output:

asdf : 4
asd : 2 
43 : 2
434 : 1
kasdf : 1
stop : 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM