How to compute the hash code for a stream in the same way as List.hashCode()

后端 未结 4 988
一整个雨季
一整个雨季 2020-12-17 21:27

I just realized that implementing the following algorithm to compute the hash code for a stream is not possible using Stream.reduce(...). The problem is that the initial see

4条回答
  •  死守一世寂寞
    2020-12-17 21:37

    Holger wrote the right solution, if you want a simple way of doing it there are two additional possibilities:

    1. collect to List and call hashCode()

    Stream stream;
    int hashCode = stream.collect(toList()).hashCode();
    

    2. use Stream.iterator()

    Stream stream;
    Iterator iter = stream.iterator();
    int hashCode = 1;
    while(iter.hasNext()) {
      hashCode = 31 *hashCode + Objects.hashCode(iter.next());
    }
    

    Just as a reminder the algorithm that List.hashCode() uses:

    int hashCode = 1;
    for (E e : list)
      hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
    

提交回复
热议问题