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

时间:2019-01-31 13:26:15

标签: java functional-programming 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)))

1 个答案:

答案 0 :(得分:2)

您需要在equals类中正确实现hashCodeWord,这要基于它所代表的单词的字符串内容。完成此操作后,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); }
}