refactor(api): replace Stream.collect(Collectors.toList()) with Stream.toList() (#977)

This commit is contained in:
brios
2026-04-29 12:29:13 +02:00
committed by GitHub
parent 2936d28582
commit 125b2c6ed5
43 changed files with 125 additions and 136 deletions
@@ -17,7 +17,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
@RestController @RestController
@@ -44,7 +43,7 @@ public class AppLibraryController {
libraries = libraryRepository.findAll(); libraries = libraryRepository.findAll();
} else { } else {
List<Long> libraryIds = user.getAssignedLibraries() != null List<Long> libraryIds = user.getAssignedLibraries() != null
? user.getAssignedLibraries().stream().map(Library::getId).collect(Collectors.toList()) ? user.getAssignedLibraries().stream().map(Library::getId).toList()
: List.of(); : List.of();
libraries = libraryRepository.findByIdIn(libraryIds); libraries = libraryRepository.findByIdIn(libraryIds);
} }
@@ -54,7 +53,7 @@ public class AppLibraryController {
long bookCount = bookRepository.countByLibraryId(library.getId()); long bookCount = bookRepository.countByLibraryId(library.getId());
return mobileBookMapper.toLibrarySummary(library, bookCount); return mobileBookMapper.toLibrarySummary(library, bookCount);
}) })
.collect(Collectors.toList()); .toList();
return ResponseEntity.ok(summaries); return ResponseEntity.ok(summaries);
} }
@@ -22,7 +22,6 @@ import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
@RestController @RestController
@@ -50,7 +49,7 @@ public class AppShelfController {
List<AppShelfSummary> summaries = shelves.stream() List<AppShelfSummary> summaries = shelves.stream()
.map(mobileBookMapper::toShelfSummaryFromEntity) .map(mobileBookMapper::toShelfSummaryFromEntity)
.collect(Collectors.toList()); .toList();
return ResponseEntity.ok(summaries); return ResponseEntity.ok(summaries);
} }
@@ -88,7 +87,7 @@ public class AppShelfController {
List<AppMagicShelfSummary> summaries = allShelves.stream() List<AppMagicShelfSummary> summaries = allShelves.stream()
.map(mobileBookMapper::toMagicShelfSummary) .map(mobileBookMapper::toMagicShelfSummary)
.collect(Collectors.toList()); .toList();
return ResponseEntity.ok(summaries); return ResponseEntity.ok(summaries);
} }
@@ -136,7 +136,7 @@ public interface AppBookMapper {
} }
return shelves.stream() return shelves.stream()
.map(this::toShelfSummary) .map(this::toShelfSummary)
.collect(Collectors.toList()); .toList();
} }
default AppShelfSummary toShelfSummary(ShelfEntity shelf) { default AppShelfSummary toShelfSummary(ShelfEntity shelf) {
@@ -280,7 +280,7 @@ public interface AppBookMapper {
.filter(bf -> bf.getBookType() != null) .filter(bf -> bf.getBookType() != null)
.map(bf -> bf.getBookType().name()) .map(bf -> bf.getBookType().name())
.distinct() .distinct()
.collect(Collectors.toList()); .toList();
} }
@Named("mapFiles") @Named("mapFiles")
@@ -319,7 +319,7 @@ public interface AppBookMapper {
.isPrimary(bf.getId().equals(primaryId)) .isPrimary(bf.getId().equals(primaryId))
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
default AppLibrarySummary toLibrarySummary(LibraryEntity library, long bookCount) { default AppLibrarySummary toLibrarySummary(LibraryEntity library, long bookCount) {
@@ -333,7 +333,7 @@ public interface AppBookMapper {
.id(lp.getId()) .id(lp.getId())
.path(lp.getPath()) .path(lp.getPath())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
return AppLibrarySummary.builder() return AppLibrarySummary.builder()
.id(library.getId()) .id(library.getId())
@@ -91,13 +91,13 @@ public class AppAuthorService {
.hasPhoto(authorHasPhoto) .hasPhoto(authorHasPhoto)
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
// Post-filter by hasPhoto if requested // Post-filter by hasPhoto if requested
if (hasPhoto != null) { if (hasPhoto != null) {
summaries = summaries.stream() summaries = summaries.stream()
.filter(s -> s.isHasPhoto() == hasPhoto) .filter(s -> s.isHasPhoto() == hasPhoto)
.collect(Collectors.toList()); .toList();
// Adjust total count for hasPhoto filter — requires a separate count // Adjust total count for hasPhoto filter — requires a separate count
long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto); long filteredTotal = countAuthorsWithPhotoFilter(accessibleLibraryIds, libraryId, search, hasPhoto);
return AppPageResponse.of(summaries, pageNum, pageSize, filteredTotal); return AppPageResponse.of(summaries, pageNum, pageSize, filteredTotal);
@@ -276,7 +276,7 @@ public class AppBookService {
return topIds.stream() return topIds.stream()
.filter(enrichedMap::containsKey) .filter(enrichedMap::containsKey)
.map(id -> mobileBookMapper.toSummary(enrichedMap.get(id), progressMap.get(id))) .map(id -> mobileBookMapper.toSummary(enrichedMap.get(id), progressMap.get(id)))
.collect(Collectors.toList()); .toList();
} }
public List<AppBookSummary> getContinueListening(Integer limit) { public List<AppBookSummary> getContinueListening(Integer limit) {
@@ -299,7 +299,7 @@ public class AppBookService {
return topIds.stream() return topIds.stream()
.filter(enrichedMap::containsKey) .filter(enrichedMap::containsKey)
.map(id -> mobileBookMapper.toSummary(enrichedMap.get(id), progressMap.get(id))) .map(id -> mobileBookMapper.toSummary(enrichedMap.get(id), progressMap.get(id)))
.collect(Collectors.toList()); .toList();
} }
public List<AppBookSummary> getRecentlyAdded(Integer limit) { public List<AppBookSummary> getRecentlyAdded(Integer limit) {
@@ -322,7 +322,7 @@ public class AppBookService {
return bookPage.getContent().stream() return bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId()))) .map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList()); .toList();
} }
public List<AppBookSummary> getRecentlyScanned(Integer limit) { public List<AppBookSummary> getRecentlyScanned(Integer limit) {
@@ -344,7 +344,7 @@ public class AppBookService {
return bookPage.getContent().stream() return bookPage.getContent().stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId()))) .map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList()); .toList();
} }
public AppPageResponse<AppBookSummary> getRandomBooks( public AppPageResponse<AppBookSummary> getRandomBooks(
@@ -406,7 +406,7 @@ public class AppBookService {
.filter(Objects::nonNull) .filter(Objects::nonNull)
.filter(BookEntity::hasFiles) .filter(BookEntity::hasFiles)
.map(bookEntity -> mobileBookMapper.toSummary(bookEntity, progressMap.get(bookEntity.getId()))) .map(bookEntity -> mobileBookMapper.toSummary(bookEntity, progressMap.get(bookEntity.getId())))
.collect(Collectors.toList()); .toList();
return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements()); return AppPageResponse.of(summaries, pageNum, pageSize, booksPage.getTotalElements());
} }
@@ -1132,7 +1132,7 @@ public class AppBookService {
List<AppBookSummary> summaries = books.stream() List<AppBookSummary> summaries = books.stream()
.map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId()))) .map(book -> mobileBookMapper.toSummary(book, progressMap.get(book.getId())))
.collect(Collectors.toList()); .toList();
return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements()); return AppPageResponse.of(summaries, pageNum, pageSize, bookPage.getTotalElements());
} }
@@ -8,7 +8,6 @@ import tools.jackson.databind.ser.BeanPropertyWriter;
import tools.jackson.databind.ser.ValueSerializerModifier; import tools.jackson.databind.ser.ValueSerializerModifier;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
/** /**
* Jackson configuration for Komga API clean mode. * Jackson configuration for Komga API clean mode.
@@ -32,8 +31,8 @@ public class JacksonConfig {
List<BeanPropertyWriter> beanProperties) { List<BeanPropertyWriter> beanProperties) {
return beanProperties.stream() return beanProperties.stream()
.map(KomgaCleanBeanPropertyWriter::new) .<BeanPropertyWriter>map(KomgaCleanBeanPropertyWriter::new)
.collect(Collectors.toList()); .toList();
} }
}) })
) )
@@ -15,7 +15,6 @@ import org.springframework.web.context.request.async.AsyncRequestNotUsableExcept
import org.springframework.web.servlet.resource.NoResourceFoundException; import org.springframework.web.servlet.resource.NoResourceFoundException;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@RestControllerAdvice @RestControllerAdvice
@@ -40,7 +39,7 @@ public class GlobalExceptionHandler {
.getFieldErrors() .getFieldErrors()
.stream() .stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage()) .map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.toList()); .toList();
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
@@ -51,7 +50,7 @@ public class GlobalExceptionHandler {
List<String> errors = ex.getConstraintViolations() List<String> errors = ex.getConstraintViolations()
.stream() .stream()
.map(violation -> violation.getPropertyPath() + ": " + violation.getMessage()) .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
.collect(Collectors.toList()); .toList();
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors); ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), "Validation error", errors);
return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
@@ -14,7 +14,6 @@ import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.ObjectMapper;
import java.util.Collections; import java.util.Collections;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Component @Component
@@ -85,7 +84,7 @@ public class BookLoreUserTransformer {
bookLoreUser.setAssignedLibraries( bookLoreUser.setAssignedLibraries(
userEntity.getLibraries().stream() userEntity.getLibraries().stream()
.map(libraryMapper::toLibrary) .map(libraryMapper::toLibrary)
.collect(Collectors.toList()) .toList()
); );
} else { } else {
bookLoreUser.setAssignedLibraries(Collections.emptyList()); bookLoreUser.setAssignedLibraries(Collections.emptyList());
@@ -17,7 +17,6 @@ import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Component @Component
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -122,14 +121,14 @@ public class KomgaMapper {
.name(author.getName()) .name(author.getName())
.role("writer") .role("writer")
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
List<String> tags = new ArrayList<>(); List<String> tags = new ArrayList<>();
if (metadata.getTags() != null) { if (metadata.getTags() != null) {
tags = metadata.getTags().stream() tags = metadata.getTags().stream()
.map(TagEntity::getName) .map(TagEntity::getName)
.collect(Collectors.toList()); .toList();
} }
return KomgaBookMetadataDto.builder() return KomgaBookMetadataDto.builder()
@@ -165,12 +164,12 @@ public class KomgaMapper {
if (firstMetadata.getCategories() != null) { if (firstMetadata.getCategories() != null) {
genres = firstMetadata.getCategories().stream() genres = firstMetadata.getCategories().stream()
.map(CategoryEntity::getName) .map(CategoryEntity::getName)
.collect(Collectors.toList()); .toList();
} }
if (firstMetadata.getTags() != null) { if (firstMetadata.getTags() != null) {
tags = firstMetadata.getTags().stream() tags = firstMetadata.getTags().stream()
.map(TagEntity::getName) .map(TagEntity::getName)
.collect(Collectors.toList()); .toList();
} }
} }
String language = firstMetadata != null ? firstMetadata.getLanguage() : null; String language = firstMetadata != null ? firstMetadata.getLanguage() : null;
@@ -233,7 +232,7 @@ public class KomgaMapper {
List<KomgaAuthorDto> authors = authorNames.stream() List<KomgaAuthorDto> authors = authorNames.stream()
.map(name -> KomgaAuthorDto.builder().name(name).role("writer").build()) .map(name -> KomgaAuthorDto.builder().name(name).role("writer").build())
.collect(Collectors.toList()); .toList();
return KomgaBookMetadataAggregationDto.builder() return KomgaBookMetadataAggregationDto.builder()
.authors(authors) .authors(authors)
@@ -20,7 +20,6 @@ import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters; import java.time.temporal.TemporalAdjusters;
import java.util.*; import java.util.*;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Service @Service
@@ -336,7 +335,7 @@ public class BookRuleEvaluatorService {
List<ReadStatus> readStatuses = statuses.stream() List<ReadStatus> readStatuses = statuses.stream()
.map(ReadStatus::valueOf) .map(ReadStatus::valueOf)
.collect(Collectors.toList()); .toList();
sub.select(cb.literal(1L)).where( sub.select(cb.literal(1L)).where(
cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")), cb.equal(subRoot.get("metadata").get("seriesName"), root.get("metadata").get("seriesName")),
@@ -741,11 +740,11 @@ public class BookRuleEvaluatorService {
boolean hasUnset = ruleList.stream().anyMatch("UNSET"::equals); boolean hasUnset = ruleList.stream().anyMatch("UNSET"::equals);
List<String> nonUnsetValues = ruleList.stream() List<String> nonUnsetValues = ruleList.stream()
.filter(v -> !"UNSET".equals(v)) .filter(v -> !"UNSET".equals(v))
.collect(Collectors.toList()); .toList();
List<ReadStatus> statuses = nonUnsetValues.stream() List<ReadStatus> statuses = nonUnsetValues.stream()
.map(ReadStatus::valueOf) .map(ReadStatus::valueOf)
.collect(Collectors.toList()); .toList();
if (hasUnset && !statuses.isEmpty()) { if (hasUnset && !statuses.isEmpty()) {
return cb.or( return cb.or(
@@ -759,7 +758,7 @@ public class BookRuleEvaluatorService {
} }
} }
List<String> lowerList = ruleList.stream().map(String::toLowerCase).collect(Collectors.toList()); List<String> lowerList = ruleList.stream().map(String::toLowerCase).toList();
return cb.lower(field.as(String.class)).in(lowerList); return cb.lower(field.as(String.class)).in(lowerList);
} }
@@ -879,7 +878,7 @@ public class BookRuleEvaluatorService {
List<String> lowerValues = values.stream() List<String> lowerValues = values.stream()
.map(String::toLowerCase) .map(String::toLowerCase)
.collect(Collectors.toList()); .toList();
subquery.select(cb.literal(1L)).where( subquery.select(cb.literal(1L)).where(
cb.equal(subRoot.get("id"), root.get("id")), cb.equal(subRoot.get("id"), root.get("id")),
@@ -947,7 +946,7 @@ public class BookRuleEvaluatorService {
if (value instanceof List) { if (value instanceof List) {
return ((Collection<?>) value).stream() return ((Collection<?>) value).stream()
.map(Object::toString) .map(Object::toString)
.collect(Collectors.toList()); .toList();
} }
return Collections.singletonList(value.toString()); return Collections.singletonList(value.toString());
@@ -10,8 +10,8 @@ import org.booklore.service.audit.AuditService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
@Service @Service
@@ -32,9 +32,9 @@ public class MagicShelfService {
} }
private List<MagicShelf> getShelvesForUser(Long userId) { private List<MagicShelf> getShelvesForUser(Long userId) {
List<MagicShelf> shelves = magicShelfRepository.findAllByUserId(userId).stream() List<MagicShelf> shelves = new ArrayList<>(magicShelfRepository.findAllByUserId(userId).stream()
.map(this::toDto) .map(this::toDto)
.collect(Collectors.toList()); .toList());
List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList(); List<Long> userShelfIds = shelves.stream().map(MagicShelf::getId).toList();
@@ -83,7 +83,7 @@ public class ReadingSessionService {
.count(e.getValue()) .count(e.getValue())
.build()) .build())
.sorted(Comparator.comparing(ReadingSessionHeatmapResponse::getDate)) .sorted(Comparator.comparing(ReadingSessionHeatmapResponse::getDate))
.collect(Collectors.toList()); .toList();
} }
private static int toSundayFirstDow(DayOfWeek dow) { private static int toSundayFirstDow(DayOfWeek dow) {
@@ -158,7 +158,7 @@ public class ReadingSessionService {
.totalSessions(dto.getTotalSessions()) .totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds()) .totalDurationSeconds(dto.getTotalDurationSeconds())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) { public List<ReadingSpeedResponse> getReadingSpeedForYear(int year) {
@@ -175,7 +175,7 @@ public class ReadingSessionService {
.avgProgressPerMinute(dto.getAvgProgressPerMinute()) .avgProgressPerMinute(dto.getAvgProgressPerMinute())
.totalSessions(dto.getTotalSessions()) .totalSessions(dto.getTotalSessions())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) { public List<PeakHoursResponse> getPeakReadingHours(Integer year, Integer month) {
@@ -198,7 +198,7 @@ public class ReadingSessionService {
.sessionCount(e.getValue()[0]) .sessionCount(e.getValue()[0])
.totalDurationSeconds(e.getValue()[1]) .totalDurationSeconds(e.getValue()[1])
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) { public List<FavoriteReadingDaysResponse> getFavoriteReadingDays(Integer year, Integer month) {
@@ -226,7 +226,7 @@ public class ReadingSessionService {
.build(); .build();
}) })
.sorted(Comparator.comparingInt(FavoriteReadingDaysResponse::getDayOfWeek)) .sorted(Comparator.comparingInt(FavoriteReadingDaysResponse::getDayOfWeek))
.collect(Collectors.toList()); .toList();
} }
public List<GenreStatisticsResponse> getGenreStatistics() { public List<GenreStatisticsResponse> getGenreStatistics() {
@@ -248,7 +248,7 @@ public class ReadingSessionService {
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0) .averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public List<CompletionTimelineResponse> getCompletionTimeline(int year) { public List<CompletionTimelineResponse> getCompletionTimeline(int year) {
@@ -286,7 +286,7 @@ public class ReadingSessionService {
int cmp = b.getYear().compareTo(a.getYear()); int cmp = b.getYear().compareTo(a.getYear());
return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth()); return cmp != 0 ? cmp : b.getMonth().compareTo(a.getMonth());
}) })
.collect(Collectors.toList()); .toList();
} }
public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page, int size) { public Page<ReadingSessionResponse> getReadingSessionsForBook(Long bookId, int page, int size) {
@@ -331,7 +331,7 @@ public class ReadingSessionService {
.month(dto.getMonth()) .month(dto.getMonth())
.count(dto.getCount()) .count(dto.getCount())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<PageTurnerScoreResponse> getPageTurnerScores() { public List<PageTurnerScoreResponse> getPageTurnerScores() {
@@ -351,7 +351,7 @@ public class ReadingSessionService {
? book.getMetadata().getCategories().stream() ? book.getMetadata().getCategories().stream()
.map(CategoryEntity::getName) .map(CategoryEntity::getName)
.sorted() .sorted()
.collect(Collectors.toList()) .toList()
: List.of(); : List.of();
bookCategories.put(book.getId(), categories); bookCategories.put(book.getId(), categories);
}); });
@@ -366,7 +366,7 @@ public class ReadingSessionService {
List<Double> durations = bookSessions.stream() List<Double> durations = bookSessions.stream()
.map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0) .map(s -> s.getDurationSeconds() != null ? s.getDurationSeconds().doubleValue() : 0.0)
.collect(Collectors.toList()); .toList();
List<Double> gaps = new ArrayList<>(); List<Double> gaps = new ArrayList<>();
for (int i = 1; i < bookSessions.size(); i++) { for (int i = 1; i < bookSessions.size(); i++) {
@@ -412,7 +412,7 @@ public class ReadingSessionService {
.build(); .build();
}) })
.sorted(Comparator.comparingInt(PageTurnerScoreResponse::getGripScore).reversed()) .sorted(Comparator.comparingInt(PageTurnerScoreResponse::getGripScore).reversed())
.collect(Collectors.toList()); .toList();
} }
private static final int COMPLETION_RACE_BOOK_LIMIT = 10; private static final int COMPLETION_RACE_BOOK_LIMIT = 10;
@@ -445,7 +445,7 @@ public class ReadingSessionService {
.sessionDate(dto.getSessionDate()) .sessionDate(dto.getSessionDate())
.endProgress(dto.getEndProgress()) .endProgress(dto.getEndProgress())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<ReadingSessionHeatmapResponse> getReadingDates() { public List<ReadingSessionHeatmapResponse> getReadingDates() {
@@ -466,7 +466,7 @@ public class ReadingSessionService {
.rating(dto.getRating()) .rating(dto.getRating())
.count(dto.getCount()) .count(dto.getCount())
.build()) .build())
.collect(Collectors.toList()); .toList();
// Status distribution // Status distribution
List<BookDistributionsResponse.StatusBucket> statusBuckets = userBookProgressRepository.findStatusDistributionByUser(userId) List<BookDistributionsResponse.StatusBucket> statusBuckets = userBookProgressRepository.findStatusDistributionByUser(userId)
@@ -475,7 +475,7 @@ public class ReadingSessionService {
.status(dto.getStatus().name()) .status(dto.getStatus().name())
.count(dto.getCount()) .count(dto.getCount())
.build()) .build())
.collect(Collectors.toList()); .toList();
// Progress distribution — coalesce to max across sources, then bucket // Progress distribution — coalesce to max across sources, then bucket
List<ProgressPercentDto> progressRows = userBookProgressRepository.findAllProgressPercentsByUser(userId); List<ProgressPercentDto> progressRows = userBookProgressRepository.findAllProgressPercentsByUser(userId);
@@ -544,7 +544,7 @@ public class ReadingSessionService {
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek())) .dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public ReadingStreakResponse getReadingStreak() { public ReadingStreakResponse getReadingStreak() {
@@ -626,7 +626,7 @@ public class ReadingSessionService {
.maxProgress(dto.getMaxProgress()) .maxProgress(dto.getMaxProgress())
.readStatus(dto.getReadStatus()) .readStatus(dto.getReadStatus())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
private double linearRegressionSlope(List<Double> values) { private double linearRegressionSlope(List<Double> values) {
@@ -671,7 +671,7 @@ public class ReadingSessionService {
.sessions(e.getValue()[0]) .sessions(e.getValue()[0])
.durationMinutes(Math.round(e.getValue()[1] / 60.0)) .durationMinutes(Math.round(e.getValue()[1] / 60.0))
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) { public List<WeeklyListeningTrendResponse> getWeeklyListeningTrend(int weeks) {
@@ -701,7 +701,7 @@ public class ReadingSessionService {
.sessions(entry.getValue()[1]) .sessions(entry.getValue()[1])
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public ListeningCompletionResponse getListeningCompletion() { public ListeningCompletionResponse getListeningCompletion() {
@@ -736,7 +736,7 @@ public class ReadingSessionService {
.totalAudiobooks(totalAudiobooks) .totalAudiobooks(totalAudiobooks)
.completed(completed) .completed(completed)
.inProgressCount(inProgressCount) .inProgressCount(inProgressCount)
.inProgress(inProgress.stream().limit(10).collect(Collectors.toList())) .inProgress(inProgress.stream().limit(10).toList())
.build(); .build();
} }
@@ -766,7 +766,7 @@ public class ReadingSessionService {
.totalListeningSeconds(listeningSeconds) .totalListeningSeconds(listeningSeconds)
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public ListeningFinishFunnelResponse getListeningFinishFunnel() { public ListeningFinishFunnelResponse getListeningFinishFunnel() {
@@ -819,7 +819,7 @@ public class ReadingSessionService {
.sessionCount(e.getValue()[0]) .sessionCount(e.getValue()[0])
.totalDurationSeconds(e.getValue()[1]) .totalDurationSeconds(e.getValue()[1])
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<GenreStatisticsResponse> getListeningGenreStatistics() { public List<GenreStatisticsResponse> getListeningGenreStatistics() {
@@ -839,7 +839,7 @@ public class ReadingSessionService {
.averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0) .averageSessionsPerBook(Math.round(avgSessionsPerBook * 100.0) / 100.0)
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public List<ListeningAuthorResponse> getListeningAuthorStats() { public List<ListeningAuthorResponse> getListeningAuthorStats() {
@@ -852,7 +852,7 @@ public class ReadingSessionService {
.totalSessions(dto.getTotalSessions()) .totalSessions(dto.getTotalSessions())
.totalDurationSeconds(dto.getTotalDurationSeconds()) .totalDurationSeconds(dto.getTotalDurationSeconds())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<SessionScatterResponse> getListeningSessionScatter() { public List<SessionScatterResponse> getListeningSessionScatter() {
@@ -869,7 +869,7 @@ public class ReadingSessionService {
.dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek())) .dayOfWeek(toSundayFirstDow(zdt.getDayOfWeek()))
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
public List<LongestAudiobookResponse> getListeningLongestBooks() { public List<LongestAudiobookResponse> getListeningLongestBooks() {
@@ -890,6 +890,6 @@ public class ReadingSessionService {
.progressPercent(Math.round(maxProg * 10.0) / 10.0) .progressPercent(Math.round(maxProg * 10.0) / 10.0)
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
} }
@@ -76,7 +76,7 @@ public class BookFileAttachmentService {
List<BookFileEntity> sourceBookFiles = sourceBook.getBookFiles().stream() List<BookFileEntity> sourceBookFiles = sourceBook.getBookFiles().stream()
.filter(BookFileEntity::isBookFormat) .filter(BookFileEntity::isBookFormat)
.collect(Collectors.toList()); .toList();
if (sourceBookFiles.isEmpty()) { if (sourceBookFiles.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has no book format files to attach"); throw ApiError.GENERIC_BAD_REQUEST.createException("Source book " + sourceBook.getId() + " has no book format files to attach");
@@ -18,7 +18,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
@Service @Service
@AllArgsConstructor @AllArgsConstructor
@@ -36,7 +35,7 @@ public class BookNoteService {
return bookNoteRepository.findByBookIdAndUserIdOrderByUpdatedAtDesc(bookId, currentUser.getId()) return bookNoteRepository.findByBookIdAndUserIdOrderByUpdatedAtDesc(bookId, currentUser.getId())
.stream() .stream()
.map(mapper::toDto) .map(mapper::toDto)
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -18,6 +18,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream;
@RequiredArgsConstructor @RequiredArgsConstructor
@Service @Service
@@ -118,7 +119,7 @@ public class BookQueryService {
private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId, boolean stripForListView) { private List<Book> mapBooksToDto(List<BookEntity> books, boolean includeDescription, Long userId, boolean stripForListView) {
return books.stream() return books.stream()
.map(book -> mapBookToDto(book, includeDescription, userId, stripForListView)) .map(book -> mapBookToDto(book, includeDescription, userId, stripForListView))
.collect(Collectors.toList()); .toList();
} }
private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId, boolean stripForListView) { private Book mapBookToDto(BookEntity bookEntity, boolean includeDescription, Long userId, boolean stripForListView) {
@@ -23,7 +23,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Stream;
@Slf4j @Slf4j
@Service @Service
@@ -43,7 +43,7 @@ public class BookReviewService {
List<BookReview> existingReviews = bookReviewRepository.findByBookMetadataBookId(bookId).stream() List<BookReview> existingReviews = bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto) .map(mapper::toDto)
.collect(Collectors.toList()); .toList();
MetadataPublicReviewsSettings reviewSettings = appSettingService.getAppSettings().getMetadataPublicReviewsSettings(); MetadataPublicReviewsSettings reviewSettings = appSettingService.getAppSettings().getMetadataPublicReviewsSettings();
@@ -67,7 +67,7 @@ public class BookReviewService {
bookRepository.save(bookEntity); bookRepository.save(bookEntity);
return bookReviewRepository.findByBookMetadataBookId(bookId).stream() return bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto) .map(mapper::toDto)
.collect(Collectors.toList()); .toList();
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to auto-fetch reviews for book {}: {}", bookId, e.getMessage()); log.warn("Failed to auto-fetch reviews for book {}: {}", bookId, e.getMessage());
@@ -86,14 +86,14 @@ public class BookReviewService {
List<MetadataProvider> providers = settings.getProviders().stream() List<MetadataProvider> providers = settings.getProviders().stream()
.filter(MetadataPublicReviewsSettings.ReviewProviderConfig::isEnabled) .filter(MetadataPublicReviewsSettings.ReviewProviderConfig::isEnabled)
.map(MetadataPublicReviewsSettings.ReviewProviderConfig::getProvider) .map(MetadataPublicReviewsSettings.ReviewProviderConfig::getProvider)
.collect(Collectors.toList()); .toList();
Map<MetadataProvider, BookMetadata> metadataMap = metadataRefreshService.fetchMetadataForBook(providers, bookEntity); Map<MetadataProvider, BookMetadata> metadataMap = metadataRefreshService.fetchMetadataForBook(providers, bookEntity);
return metadataMap.values().stream() return metadataMap.values().stream()
.filter(meta -> meta.getBookReviews() != null) .filter(meta -> meta.getBookReviews() != null)
.flatMap(meta -> meta.getBookReviews().stream()) .flatMap(meta -> meta.getBookReviews().stream())
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -120,7 +120,7 @@ public class BookReviewService {
return bookReviewRepository.findByBookMetadataBookId(bookId).stream() return bookReviewRepository.findByBookMetadataBookId(bookId).stream()
.map(mapper::toDto) .map(mapper::toDto)
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -166,7 +166,7 @@ public class BookService {
fileProgressMap.get(bookEntity.getId()) fileProgressMap.get(bookEntity.getId())
); );
return book; return book;
}).collect(Collectors.toList()); }).toList();
} }
public Book getBook(long bookId, boolean withDescription) { public Book getBook(long bookId, boolean withDescription) {
@@ -233,7 +233,7 @@ public class BookUpdateService {
BookLoreUserEntity userEntity = findUserOrThrow(userId); BookLoreUserEntity userEntity = findUserOrThrow(userId);
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream() List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
.map(bookId -> createProgressEntity(userEntity, bookId, status, now, dateFinished)) .map(bookId -> createProgressEntity(userEntity, bookId, status, now, dateFinished))
.collect(Collectors.toList()); .toList();
userBookProgressRepository.saveAll(newProgressEntities); userBookProgressRepository.saveAll(newProgressEntities);
} }
@@ -262,7 +262,7 @@ public class BookUpdateService {
BookLoreUserEntity userEntity = findUserOrThrow(userId); BookLoreUserEntity userEntity = findUserOrThrow(userId);
List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream() List<UserBookProgressEntity> newProgressEntities = newProgressBookIds.stream()
.map(bookId -> createProgressEntityWithRating(userEntity, bookId, rating)) .map(bookId -> createProgressEntityWithRating(userEntity, bookId, rating))
.collect(Collectors.toList()); .toList();
userBookProgressRepository.saveAll(newProgressEntities); userBookProgressRepository.saveAll(newProgressEntities);
} }
@@ -306,7 +306,7 @@ public class BookUpdateService {
return bookEntities.stream() return bookEntities.stream()
.map(bookEntity -> buildBook(bookEntity, userId, progressMap, fileProgressMap)) .map(bookEntity -> buildBook(bookEntity, userId, progressMap, fileProgressMap))
.collect(Collectors.toList()); .toList();
} }
private Book buildBook(BookEntity bookEntity, Long userId, private Book buildBook(BookEntity bookEntity, Long userId,
@@ -350,7 +350,7 @@ public class BookUpdateService {
.readStatusModifiedTime(now) .readStatusModifiedTime(now)
.dateFinished(dateFinished) .dateFinished(dateFinished)
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
private List<PersonalRatingUpdateResponse> buildRatingUpdateResponses(List<Long> bookIds, Integer rating) { private List<PersonalRatingUpdateResponse> buildRatingUpdateResponses(List<Long> bookIds, Integer rating) {
@@ -359,7 +359,7 @@ public class BookUpdateService {
.bookId(bookId) .bookId(bookId)
.personalRating(rating) .personalRating(rating)
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) { private Set<Shelf> filterShelvesByUserId(Set<Shelf> shelves, Long userId) {
@@ -28,7 +28,7 @@ import java.time.LocalDateTime;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Stream;
@Slf4j @Slf4j
@Service @Service
@@ -117,7 +117,7 @@ public class CustomFontService {
List<CustomFontEntity> fonts = customFontRepository.findByUserId(userId); List<CustomFontEntity> fonts = customFontRepository.findByUserId(userId);
return fonts.stream() return fonts.stream()
.map(customFontMapper::toDto) .map(customFontMapper::toDto)
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -12,7 +12,6 @@ import java.nio.file.Paths;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@Slf4j @Slf4j
@@ -54,7 +53,7 @@ public class PathService {
.filter(Files::isDirectory) .filter(Files::isDirectory)
.map(p -> directory.resolve(p.getFileName()).toString()) .map(p -> directory.resolve(p.getFileName()).toString())
.sorted() .sorted()
.collect(Collectors.toList()); .toList();
} catch (IOException e) { } catch (IOException e) {
log.error("Error accessing path {}: {}", path, e.getMessage(), e); log.error("Error accessing path {}: {}", path, e.getMessage(), e);
return Collections.emptyList(); return Collections.emptyList();
@@ -279,6 +279,6 @@ public class AudiobookProcessor extends AbstractFileProcessor implements BookFil
.endTimeMs(ch.getEndTimeMs()) .endTimeMs(ch.getEndTimeMs())
.durationMs(ch.getDurationMs()) .durationMs(ch.getDurationMs())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
} }
@@ -67,7 +67,7 @@ public class KoboEntitlementService {
.readingState(getReadingStateForBook(book)) .readingState(getReadingStateForBook(book))
.build()) .build())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<? extends Entitlement> generateChangedEntitlements(Set<Long> bookIds, String token, boolean removed) { public List<? extends Entitlement> generateChangedEntitlements(Set<Long> bookIds, String token, boolean removed) {
@@ -95,7 +95,7 @@ public class KoboEntitlementService {
.build()) .build())
.build(); .build();
}) })
.collect(Collectors.toList()); .toList();
} }
return books.stream() return books.stream()
.filter(bookEntity -> bookEntity.getPrimaryBookFile() != null && bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB) .filter(bookEntity -> bookEntity.getPrimaryBookFile() != null && bookEntity.getPrimaryBookFile().getBookType() == BookFileType.EPUB)
@@ -105,7 +105,7 @@ public class KoboEntitlementService {
.bookMetadata(mapToKoboMetadata(book, token)) .bookMetadata(mapToKoboMetadata(book, token))
.build()) .build())
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) { public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
@@ -16,7 +16,6 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
@AllArgsConstructor @AllArgsConstructor
@Service @Service
@@ -143,7 +142,7 @@ public class KoboLibrarySnapshotService {
snapshotBook.setMetadataUpdatedAt(book.getMetadataUpdatedAt()); snapshotBook.setMetadataUpdatedAt(book.getMetadataUpdatedAt());
return snapshotBook; return snapshotBook;
}) })
.collect(Collectors.toList()); .toList();
} }
private boolean isBookOwnedByUser(BookEntity book, Long userId) { private boolean isBookOwnedByUser(BookEntity book, Long userId) {
@@ -30,7 +30,6 @@ import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit; import java.time.temporal.ChronoUnit;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Service @Service
@@ -70,7 +69,7 @@ public class KoboReadingStateService {
.statisticsResult(KoboReadingStateResponse.Result.success()) .statisticsResult(KoboReadingStateResponse.Result.success())
.statusInfoResult(KoboReadingStateResponse.Result.success()) .statusInfoResult(KoboReadingStateResponse.Result.success())
.build()) .build())
.collect(Collectors.toList()); .toList();
return KoboReadingStateResponse.builder() return KoboReadingStateResponse.builder()
.requestResult("Success") .requestResult("Success")
@@ -120,7 +119,7 @@ public class KoboReadingStateService {
return savedState; return savedState;
}) })
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -30,7 +30,7 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.*; import java.util.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Stream;
@Slf4j @Slf4j
@Service @Service
@@ -50,7 +50,7 @@ public class KomgaService {
public List<KomgaLibraryDto> getAllLibraries() { public List<KomgaLibraryDto> getAllLibraries() {
return libraryRepository.findAll().stream() return libraryRepository.findAll().stream()
.map(komgaMapper::toKomgaLibraryDto) .map(komgaMapper::toKomgaLibraryDto)
.collect(Collectors.toList()); .toList();
} }
public KomgaLibraryDto getLibraryById(Long libraryId) { public KomgaLibraryDto getLibraryById(Long libraryId) {
@@ -258,7 +258,7 @@ public class KomgaService {
// Return all books without pagination // Return all books without pagination
content = seriesBooks.stream() content = seriesBooks.stream()
.map(book -> komgaMapper.toKomgaBookDto(book)) .map(book -> komgaMapper.toKomgaBookDto(book))
.collect(Collectors.toList()); .toList();
actualPage = 0; actualPage = 0;
actualSize = totalElements; actualSize = totalElements;
totalPages = totalElements > 0 ? 1 : 0; totalPages = totalElements > 0 ? 1 : 0;
@@ -270,7 +270,7 @@ public class KomgaService {
content = seriesBooks.subList(fromIndex, toIndex).stream() content = seriesBooks.subList(fromIndex, toIndex).stream()
.map(book -> komgaMapper.toKomgaBookDto(book)) .map(book -> komgaMapper.toKomgaBookDto(book))
.collect(Collectors.toList()); .toList();
actualPage = page; actualPage = page;
actualSize = size; actualSize = size;
} }
@@ -300,7 +300,7 @@ public class KomgaService {
List<KomgaBookDto> content = bookPage.getContent().stream() List<KomgaBookDto> content = bookPage.getContent().stream()
.map(book -> komgaMapper.toKomgaBookDto(book)) .map(book -> komgaMapper.toKomgaBookDto(book))
.collect(Collectors.toList()); .toList();
return KomgaPageableDto.<KomgaBookDto>builder() return KomgaPageableDto.<KomgaBookDto>builder()
.content(content) .content(content)
@@ -364,7 +364,7 @@ public class KomgaService {
List<KomgaCollectionDto> allCollections = magicShelves.stream() List<KomgaCollectionDto> allCollections = magicShelves.stream()
.map(shelf -> komgaMapper.toKomgaCollectionDto(shelf, 0)) .map(shelf -> komgaMapper.toKomgaCollectionDto(shelf, 0))
.sorted(Comparator.comparing(KomgaCollectionDto::getName)) .sorted(Comparator.comparing(KomgaCollectionDto::getName))
.collect(Collectors.toList()); .toList();
log.debug("Mapped to {} collection DTOs", allCollections.size()); log.debug("Mapped to {} collection DTOs", allCollections.size());
@@ -42,7 +42,7 @@ public class BookRestorationService {
List<BookEntity> toRestore = deletedBooks.stream() List<BookEntity> toRestore = deletedBooks.stream()
.filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty()) .filter(book -> book.getBookFiles() != null && !book.getBookFiles().isEmpty())
.filter(book -> currentPaths.contains(book.getFullFilePath())) .filter(book -> currentPaths.contains(book.getFullFilePath()))
.collect(Collectors.toList()); .toList();
if (toRestore.isEmpty()) return; if (toRestore.isEmpty()) return;
@@ -51,7 +51,7 @@ public class LibraryFileHelper {
return !currentFullPaths.contains(book.getFullFilePath()); return !currentFullPaths.contains(book.getFullFilePath());
}) })
.map(BookEntity::getId) .map(BookEntity::getId)
.collect(Collectors.toList()); .toList();
} }
public List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, List<BookFileEntity> allAdditionalFiles) { public List<Long> detectDeletedAdditionalFiles(List<LibraryFile> libraryFiles, List<BookFileEntity> allAdditionalFiles) {
@@ -63,7 +63,7 @@ public class LibraryFileHelper {
.filter(BookFileEntity::isBookFormat) .filter(BookFileEntity::isBookFormat)
.filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile))) .filter(additionalFile -> !currentFileKeys.contains(generateUniqueKey(additionalFile)))
.map(BookFileEntity::getId) .map(BookFileEntity::getId)
.collect(Collectors.toList()); .toList();
} }
public List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, List<BookFileEntity> allAdditionalFiles) { public List<LibraryFile> detectNewBookPaths(List<LibraryFile> libraryFiles, List<BookEntity> books, List<BookFileEntity> allAdditionalFiles) {
@@ -80,7 +80,7 @@ public class LibraryFileHelper {
return libraryFiles.stream() return libraryFiles.stream()
.filter(file -> !existingKeys.contains(generateUniqueKey(file))) .filter(file -> !existingKeys.contains(generateUniqueKey(file)))
.collect(Collectors.toList()); .toList();
} }
private String generateUniqueKey(BookEntity book) { private String generateUniqueKey(BookEntity book) {
@@ -227,7 +227,7 @@ public class LibraryFileHelper {
Set<BookFileType> allowed = EnumSet.copyOf(allowedFormats); Set<BookFileType> allowed = EnumSet.copyOf(allowedFormats);
return files.stream() return files.stream()
.filter(file -> allowed.contains(file.getBookFileType())) .filter(file -> allowed.contains(file.getBookFileType()))
.collect(java.util.stream.Collectors.toList()); .toList();
} }
private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException { private List<LibraryFile> findLibraryFiles(LibraryPathEntity pathEntity, LibraryEntity libraryEntity) throws IOException {
@@ -72,7 +72,7 @@ public class LibraryService {
@Transactional @Transactional
@EventListener(ApplicationReadyEvent.class) @EventListener(ApplicationReadyEvent.class)
public void initializeMonitoring() { public void initializeMonitoring() {
List<Library> libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).collect(Collectors.toList()); List<Library> libraries = libraryRepository.findAll().stream().map(libraryMapper::toLibrary).toList();
libraryWatchService.registerLibraries(libraries); libraryWatchService.registerLibraries(libraries);
log.info("Monitoring initialized with {} libraries", libraries.size()); log.info("Monitoring initialized with {} libraries", libraries.size());
} }
@@ -156,14 +156,16 @@ public class LibraryService {
BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId()) BookLoreUserEntity userEntity = userRepository.findById(bookLoreUser.getId())
.orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId())); .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(bookLoreUser.getId()));
// Stream.toList() returns an unmodifiable list, while JPA/Hibernate requires a mutable collection for entity
// relationship fields
LibraryEntity libraryEntity = LibraryEntity.builder() LibraryEntity libraryEntity = LibraryEntity.builder()
.name(request.getName()) .name(request.getName())
.libraryPaths( .libraryPaths(
request.getPaths() == null || request.getPaths().isEmpty() ? request.getPaths() == null || request.getPaths().isEmpty() ?
Collections.emptyList() : Collections.emptyList() :
request.getPaths().stream() new ArrayList<>(request.getPaths().stream()
.map(path -> LibraryPathEntity.builder().path(path.getPath()).build()) .map(path -> LibraryPathEntity.builder().path(path.getPath()).build())
.collect(Collectors.toList()) .toList())
) )
.icon(request.getIcon()) .icon(request.getIcon())
.iconType(request.getIconType()) .iconType(request.getIconType())
@@ -44,7 +44,6 @@ import org.booklore.model.dto.request.IsbnLookupRequest;
import java.io.File; import java.io.File;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@Slf4j @Slf4j
@@ -207,7 +206,7 @@ public class BookMetadataService {
.peek(book -> book.getMetadata().applyLockToAllFields(lock)) .peek(book -> book.getMetadata().applyLockToAllFields(lock))
.toList(); .toList();
bookRepository.saveAll(books); bookRepository.saveAll(books);
return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList()); return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).toList();
} }
public BookMetadata getComicInfoMetadata(long bookId) { public BookMetadata getComicInfoMetadata(long bookId) {
@@ -685,7 +685,7 @@ public class MetadataRefreshService {
List<BookReview> allReviews = metadataMap.values().stream() List<BookReview> allReviews = metadataMap.values().stream()
.filter(Objects::nonNull) .filter(Objects::nonNull)
.flatMap(md -> Optional.ofNullable(md.getBookReviews()).stream().flatMap(Collection::stream)) .flatMap(md -> Optional.ofNullable(md.getBookReviews()).stream().flatMap(Collection::stream))
.collect(Collectors.toList()); .toList();
if (!allReviews.isEmpty()) { if (!allReviews.isEmpty()) {
metadata.setBookReviews(allReviews); metadata.setBookReviews(allReviews);
} }
@@ -494,7 +494,7 @@ public class ComicvineBookParser implements BookParser, DetailedMetadataProvider
if (response != null && response.getResults() != null) { if (response != null && response.getResults() != null) {
return response.getResults().stream() return response.getResults().stream()
.map(comic -> convertToBookMetadata(comic, null)) .map(comic -> convertToBookMetadata(comic, null))
.collect(Collectors.toList()); .toList();
} }
return Collections.emptyList(); return Collections.emptyList();
} }
@@ -200,7 +200,7 @@ public class GoogleParser implements BookParser {
return results.stream() return results.stream()
.filter(this::isRelevantResult) .filter(this::isRelevantResult)
.collect(Collectors.toList()); .toList();
} }
private boolean isRelevantResult(BookMetadata metadata) { private boolean isRelevantResult(BookMetadata metadata) {
@@ -231,7 +231,7 @@ public class GoogleParser implements BookParser {
if (googleBooksApiResponse != null && googleBooksApiResponse.getItems() != null) { if (googleBooksApiResponse != null && googleBooksApiResponse.getItems() != null) {
return googleBooksApiResponse.getItems().stream() return googleBooksApiResponse.getItems().stream()
.map(this::convertToFetchedBookMetadata) .map(this::convertToFetchedBookMetadata)
.collect(Collectors.toList()); .toList();
} }
return List.of(); return List.of();
} }
@@ -619,7 +619,7 @@ public class GoogleParser implements BookParser {
.sorted((a, b) -> Integer.compare( .sorted((a, b) -> Integer.compare(
countPopulatedFields(b), countPopulatedFields(b),
countPopulatedFields(a))) countPopulatedFields(a)))
.collect(Collectors.toList()); .toList();
} }
private int countPopulatedFields(BookMetadata metadata) { private int countPopulatedFields(BookMetadata metadata) {
@@ -171,7 +171,7 @@ public class RanobeDbParser implements BookParser {
} else { } else {
return searchResponse.getBooks().stream() return searchResponse.getBooks().stream()
.map(book -> searchResultToBookMetadata(book.getId())) .map(book -> searchResultToBookMetadata(book.getId()))
.collect(Collectors.toList()); .toList();
} }
} }
@@ -464,7 +464,7 @@ public class OpdsBookService {
List<BookEntity> orderedEntities = idPage.getContent().stream() List<BookEntity> orderedEntities = idPage.getContent().stream()
.map(bookMap::get) .map(bookMap::get)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.collect(Collectors.toList()); .toList();
if (userId != null) { if (userId != null) {
orderedEntities = contentRestrictionService.applyRestrictions(orderedEntities, userId); orderedEntities = contentRestrictionService.applyRestrictions(orderedEntities, userId);
@@ -480,7 +480,7 @@ public class OpdsBookService {
private Page<Book> applyBookFilters(Page<Book> books, Long userId) { private Page<Book> applyBookFilters(Page<Book> books, Long userId) {
List<Book> filtered = books.getContent().stream() List<Book> filtered = books.getContent().stream()
.map(book -> filterBook(book, userId)) .map(book -> filterBook(book, userId))
.collect(Collectors.toList()); .toList();
return new PageImpl<>(filtered, books.getPageable(), books.getTotalElements()); return new PageImpl<>(filtered, books.getPageable(), books.getTotalElements());
} }
@@ -499,7 +499,7 @@ public class ReadingProgressService {
.readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null) .readStatusModifiedTime(existingBookIds.contains(bookId) ? now : null)
.dateFinished(null) .dateFinished(null)
.build()) .build())
.collect(Collectors.toList()); .toList();
} }
private BookLoreUserEntity findUserOrThrow(Long userId) { private BookLoreUserEntity findUserOrThrow(Long userId) {
@@ -78,7 +78,7 @@ public class BookRecommendationService {
}) })
.filter(Objects::nonNull) .filter(Objects::nonNull)
.limit(limit) .limit(limit)
.collect(Collectors.toList()); .toList();
} }
protected Set<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) { protected Set<BookRecommendationLite> findSimilarBookIds(Long bookId, int limit) {
@@ -14,7 +14,7 @@ import tools.jackson.databind.ObjectMapper;
import java.util.*; import java.util.*;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.stream.Collectors; import java.util.stream.Stream;
@Slf4j @Slf4j
@Service @Service
@@ -143,7 +143,7 @@ public class BookVectorService {
return candidates.stream() return candidates.stream()
.sorted(Comparator.comparingDouble(ScoredBook::getScore).reversed()) .sorted(Comparator.comparingDouble(ScoredBook::getScore).reversed())
.limit(k) .limit(k)
.collect(Collectors.toList()); .toList();
} }
@Getter @Getter
@@ -32,7 +32,7 @@ public class ContentRestrictionService {
public List<ContentRestriction> getUserRestrictions(Long userId) { public List<ContentRestriction> getUserRestrictions(Long userId) {
return restrictionRepository.findByUserId(userId).stream() return restrictionRepository.findByUserId(userId).stream()
.map(this::toDto) .map(this::toDto)
.collect(Collectors.toList()); .toList();
} }
public ContentRestriction getRestriction(Long restrictionId) { public ContentRestriction getRestriction(Long restrictionId) {
@@ -75,11 +75,11 @@ public class ContentRestrictionService {
.mode(r.getMode()) .mode(r.getMode())
.value(r.getValue()) .value(r.getValue())
.build()) .build())
.collect(Collectors.toList()); .toList();
return restrictionRepository.saveAll(entities).stream() return restrictionRepository.saveAll(entities).stream()
.map(this::toDto) .map(this::toDto)
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -118,7 +118,7 @@ public class ContentRestrictionService {
.filter(book -> !hasExcludedContent(book, excludedCategories, excludedTags, excludedMoods, excludedContentRatings)) .filter(book -> !hasExcludedContent(book, excludedCategories, excludedTags, excludedMoods, excludedContentRatings))
.filter(book -> matchesAllowList(book, allowedCategories, allowedTags, allowedMoods, allowedContentRatings)) .filter(book -> matchesAllowList(book, allowedCategories, allowedTags, allowedMoods, allowedContentRatings))
.filter(book -> isWithinAgeRating(book, maxAgeRating)) .filter(book -> isWithinAgeRating(book, maxAgeRating))
.collect(Collectors.toList()); .toList();
} }
private Set<String> getValuesForTypeAndMode(List<UserContentRestrictionEntity> restrictions, private Set<String> getValuesForTypeAndMode(List<UserContentRestrictionEntity> restrictions,
@@ -129,7 +129,7 @@ public class TaskService {
} }
return metadata; return metadata;
}) })
.collect(Collectors.toList()); .toList();
} }
public void executeCronTask(TaskType taskType) { public void executeCronTask(TaskType taskType) {
@@ -26,7 +26,6 @@ import tools.jackson.databind.ObjectMapper;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -45,7 +44,7 @@ public class UserService {
return userRepository.findAllWithDetails() return userRepository.findAllWithDetails()
.stream() .stream()
.map(bookLoreUserTransformer::toDTO) .map(bookLoreUserTransformer::toDTO)
.collect(Collectors.toList()); .toList();
} }
@Transactional @Transactional
@@ -132,7 +132,7 @@ public class BookRecommendationUpdaterTask implements Task {
return new BookVectorService.ScoredBook(candidateId, similarity); return new BookVectorService.ScoredBook(candidateId, similarity);
}) })
.filter(scored -> scored.getScore() > 0.1) .filter(scored -> scored.getScore() > 0.1)
.collect(Collectors.toList()); .toList();
List<BookVectorService.ScoredBook> topSimilar = vectorService.findTopKSimilar( List<BookVectorService.ScoredBook> topSimilar = vectorService.findTopKSimilar(
targetVector, targetVector,
@@ -585,7 +585,7 @@ class HibernateRegressionTest {
List<String> pathStrings = loaded.getLibraryPaths().stream() List<String> pathStrings = loaded.getLibraryPaths().stream()
.map(LibraryPathEntity::getPath) .map(LibraryPathEntity::getPath)
.collect(Collectors.toList()); .toList();
assertThat(pathStrings).containsExactlyInAnyOrder("/books", "/audiobooks"); assertThat(pathStrings).containsExactlyInAnyOrder("/books", "/audiobooks");
} }
@@ -6,7 +6,6 @@ import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.Assertions; import org.assertj.core.api.Assertions;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
public class LibraryTestBuilderAssert extends AbstractAssert<LibraryTestBuilderAssert, LibraryTestBuilder> { public class LibraryTestBuilderAssert extends AbstractAssert<LibraryTestBuilderAssert, LibraryTestBuilder> {
@@ -46,7 +45,7 @@ public class LibraryTestBuilderAssert extends AbstractAssert<LibraryTestBuilderA
.filter(a -> !a.equals(book.getPrimaryBookFile())) .filter(a -> !a.equals(book.getPrimaryBookFile()))
.map(BookFileEntity::getBookType) .map(BookFileEntity::getBookType)
.filter(a -> a != null) .filter(a -> a != null)
.collect(Collectors.toList()); .toList();
Assertions.assertThat(additionalFormatTypesActual) Assertions.assertThat(additionalFormatTypesActual)
.describedAs("Book '%s' should have additional formats: %s", bookTitle, additionalFormatTypes) .describedAs("Book '%s' should have additional formats: %s", bookTitle, additionalFormatTypes)
@@ -90,7 +89,7 @@ public class LibraryTestBuilderAssert extends AbstractAssert<LibraryTestBuilderA
.filter(a -> !a.equals(book.getPrimaryBookFile())) .filter(a -> !a.equals(book.getPrimaryBookFile()))
.map(BookFileEntity::getBookType) .map(BookFileEntity::getBookType)
.filter(a -> a != null) .filter(a -> a != null)
.collect(Collectors.toList()); .toList();
Assertions.assertThat(additionalFormatTypesActual) Assertions.assertThat(additionalFormatTypesActual)
.describedAs("Book '%s' should have no additional formats", bookTitle) .describedAs("Book '%s' should have no additional formats", bookTitle)