Grouping by object value, counting and then setting group key by maximum object attribute

前端 未结 4 970
误落风尘
误落风尘 2020-11-28 14:53

I have managed to write a solution using Java 8 Streams API that first groups a list of object Route by its value and then counts the number of objects in each group. It ret

4条回答
  •  悲哀的现实
    2020-11-28 15:24

    Changed equals and hashcode to be dependent only on start cell and end cell.

    @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Cell cell = (Cell) o;
    
            if (a != cell.a) return false;
            if (b != cell.b) return false;
    
            return true;
        }
    
        @Override
        public int hashCode() {
            int result = a;
            result = 31 * result + b;
            return result;
        }
    

    My solution looks like this:

    Map routesCounted = routes.stream()
                .sorted((r1,r2)-> (int)(r2.lastUpdated - r1.lastUpdated))
                .collect(Collectors.groupingBy(gr -> gr, Collectors.counting()));
    

    Of course casting to int should be replaced with something more appropriated.

提交回复
热议问题