I have a class that has two fields as shown below
I want to convert this class into Map<SomeClass::getField1, Set<SomeClass::getField2>>
Any idea how to write a lambda for this?
I'll be grateful for any help
@Getter
@Setter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public SomeClass {
@NotBlank
String field1;
@NotBlank
String field2;
}
You need to combine Collectors.groupingBy with Collectors.mapping and Collectors.toSet:
List<SomeClass> list = List.of();
Map<String, Set<String>> map = list.stream()
.collect(Collectors.groupingBy(
SomeClass::getField1,
Collectors.mapping(
SomeClass::getField2, // convert
Collectors.toSet() // then collect as set
)
));