在 Vavr 中将字符串组合在一起

Grouping strings together in Vavr

我正在尝试以下代码:

final Map<Word, List<Word>> tuple2s = lowercase
            .groupBy(identity());

但这会创建单个字符串组,基本上就像做 #split:

LinkedHashMap((lorem, List(lorem)), (ipsum, List(ipsum)), (lorem, List(lorem)), (lorem, List(lorem)), (ipsum, List(ipsum)), (dolor, List(dolor)), (sit, List(sit)), (dolor, List(dolor)), (sit, List(sit)), (dolor, List(dolor)), (elit, List(elit)))

我该如何解决这个问题?预期值为

LinkedHashMap((lorem, List(lorem, lorem, lorem)), (ipsum, List(ipsum, ipsum)), (dolor, List(dolor, dolor, dolor)), (sit, List(sit, sit)), (elit, List(elit)))

您需要在 Word class 中正确实现 equalshashCode,这是基于它所代表的单词的字符串内容。有了它,List.groupBy(...) 将产生您所期望的结果。类似于以下内容就足够了。

public class Word {
    private String word;

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

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Word other = (Word) o;
        return Objects.equals(word, other.word);
    }

    @Override
    public int hashCode() { return Objects.hash(word); }
}