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
The easiest and shortest way I found was to implement a Collector using Collectors.reducing:
/**
* Creates a new Collector that collects the hash code of the elements.
* @param the type of the input elements
* @return the hash code
* @see Arrays#hashCode(java.lang.Object[])
* @see AbstractList#hashCode()
*/
public static Collector toHashCode() {
return Collectors.reducing(1, Objects::hashCode, (i, j) -> 31 * i + j);
}
@Test
public void testHashCode() {
List> list = Arrays.asList(Math.PI, 42, "stackoverflow.com");
int expected = list.hashCode();
int actual = list.stream().collect(StreamUtils.toHashCode());
assertEquals(expected, actual);
}