有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何限制Flux<Map<K,V>>中元素的数量,并将其映射到自定义结果

比如说,我有一些课程来说明歌曲和投票的问题

用户。爪哇

@EqualsAndHashCode
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Document(collection = "users")
public class User {

  @Id private String id;

  private String username;

  private String email;

  private Integer age;

  private String password;

  @DBRef(db = "interview", lazy = true)
  @EqualsAndHashCode.Exclude
  @ToString.Exclude
  private Set<Song> songs;
}

歌。爪哇

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Song {

  @Id private String id;

  private String title;

  private String author;

  private SongGenre songGenre;

  Set<Vote> votesOfSong;
}

投票。爪哇

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "votes")
@Getter
public class Vote {

  @Id private String id;

  private User user;

  private Song song;

  private VoteKind voteKind;

  @Default private LocalDateTime dateOfVote = LocalDateTime.now();
}

沃特金。爪哇

@RequiredArgsConstructor
@Getter
public enum VoteKind {
  LIKE(1),
  DISLIKE(-1);

  private final Integer voteValue;
}

我想创建一个方法,它将返回特定歌曲最常见的SongGenreSongTitle和投票数

到目前为止,我有以下几种方法:

public Flux<Map<Song, SongGenre>> theMostCommonSongForSongGenre(SongGenre songGenre) {
    voteRepository
        .findAll()
        .collect(
            Collectors.toMap(vote -> vote.getSong().getSongGenre(), this::getSumOfVotesForVote))
        .map(Map::entrySet)
        .flatMapMany(Flux::fromIterable)
        .filter(stringListEntry -> stringListEntry.getKey().equals(songGenre))
        .sort(Map.Entry.comparingByKey(Comparator.reverseOrder()))
        .collect(Collectors.toMap(o -> o.getKey(), o -> o.getValue()));
  }

和助手方法:

  private int getSumOfVotesForSong(Vote vote) {
    return vote.getSong().getVotesOfSong().stream()
        .mapToInt(voteKind -> vote.getVoteKind().getVoteValue())
        .sum();
  }

这里有两个问题我不能完全解决

  1. 如何将我的流量结果限制为1或10条记录。按照常规方式,在Java流API中,我可以使用方法findFirstlimit,但这里没有其他等效方法。我唯一能调用的方法是limitRate,但它有另一个预定

  2. 如何将当前解决方案转换为返回特定歌曲的SongGenreSongTitle和票数。是否有机会为上述参数返回MultiMap,或者我应该使用groupingBy并返回一个自定义对象,其中songGenresongTitle作为键和值整数,这将等同于投票数

编辑: 核心java流解决方案可以是理想的

对于如何实现目标的建议,我将不胜感激


共 (0) 个答案