Issue
I want to valid 1 form from backend in java spring boot. When the ListUser of the form is duplicated, it will send an error message and not reload the page. I have a class request
public class StoreInformationRequest {
private Boolean isReceiveReport;
private List<String> ipAddress;
private List<Integer> listUser;
public StoreInformationRequest(Boolean isReceiveReport, List<String> ipAddress, List<Integer> listUser) {
this.isReceiveReport = isReceiveReport;
this.ipAddress = ipAddress;
this.listUser = listUser;
}
}
and Controller :
public String updateStore(@PathVariable("storeCode") String storeCode, @Valid StoreInformationRequest storeInformationRequests, RedirectAttributes attributes)
Solution
Discarding the duplicates
If you simply want to discard the duplicates, use a Set<T>
instead of a List<T>
. From the Set<T>
documentation:
A collection that contains no duplicate elements.
To discard the duplicates, you can use:
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4);
Set<Integer> unique = new HashSet<>(numbers);
You also could use:
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4);
List<Integer> unique = numbers.stream()
.distinct()
.collect(Collectors.toList());
Finding the duplicates
If you have a list and want to extract the duplicates, you can use the following:
List<Integer> numbers = Arrays.asList(1, 2, 3, 3, 4, 4);
List<Integer> duplicates = numbers.stream()
.filter(n -> Collections.frequency(numbers, n) > 1)
.distinct()
.collect(Collectors.toList());
Using Hibernate Validator
If you are using Hibernate Validator, a Bean Validation implementation, you could use @UniqueElements
to validate that every element in the collection is unique.
To use it, ensure your list is annotated with @UniqueElements
:
@Data
public class LotteryBet {
@UniqueElements
private List<Integer> numbers;
}
Then ensure your controller is annotated with @Validated
and the lotteryBet
parameter is annotated with both @RequestBody
and @Valid
:
@Validated
@RestController
@RequestMapping("/lottery")
public class LotteryController {
@PostMapping(path = "/bets", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Void> bet(@RequestBody @Valid LotteryBet lotteryBet) {
...
}
}
A request such as the one shown below will return 400
along with some details about the error:
POST /lottery/bets HTTP/1.1
Host: example.org
Content-Type: application/json
{
"numbers": [1, 2, 3, 3, 4, 4]
}
Answered By - cassiomolin
Answer Checked By - Candace Johnson (JavaFixing Volunteer)