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

后端 未结 4 992
一整个雨季
一整个雨季 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:35

    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);
    }
    

提交回复
热议问题