问题
Consider this class:
@Data
@AllArgsConstructor
@NoArgsConstructor
class User {
String name;
String languages;
}
I have a List<User>
and I would like to reduce on languages. Input:
List<User> list = new ArrayList<>();
list.add(new User("sam", "java"));
list.add(new User("sam", "js"));
list.add(new User("apollo", "html"));
Expected output:
[User(name=apollo, languages=html), User(name=sam, languages=java, js)]
I can achieve this using following code:
List<User> l = list.stream()
.collect(Collectors.groupingBy(
u -> u.name,
Collectors.reducing((u1, u2) ->
new User(u1.name, u1.languages + ", " + u2.languages))))
.values()
.stream()
.filter(user -> user.get() != null)
.map(user -> user.get())
.collect(Collectors.toList());
System.out.println(l);
But I don't want to create two stream, can this be achieved using a single stream?
回答1:
But I don't want to create two stream, can this be achieved using a single stream?
Of course it is possible, you have two options and in both you have to use Collect.collectingAndThen
that extracts the correct value type from a created Map
.
You need to use the following lambda expression first:
BinaryOperator<User> binaryOperator = (u1, u2) ->
new User(u1.getName(), String.join(", ", u1.getLanguages(), u2.getLanguages()));
The solutions:
Collectors.toMap
withCollectors.collectingAndThen
extracting values from theMap<String, User>
:List<User> l = list.stream() // Stream<User> .collect(Collectors.collectingAndThen( Collectors.toMap( // Map User::getName, // ..name as key user -> new User(user.getName(), user.getLanguages()), // ..value as user binaryOperator), // ..combined map -> new ArrayList<>(map.values()))); // extracted value
Collectors.groupingBy
withCollectors.collectingAndThen
extracting values from theMap<String, Optional<User>>
caused byCollectors.reducing
:List<User> ll = list.stream() // Stream<User> .collect(Collectors.collectingAndThen( Collectors.groupingBy( // Map<String, Optional<User>> User::getName, // ... name as key Collectors.reducing(binaryOperator)), // ... reduced value map -> map.values().stream() // extracted value .filter(Optional::isPresent) // ... where is Optional present .map(Optional::get) // ... get it .collect(Collectors.toList()))); // ... create a List<User>
Note I suppose you use java-8, there might be a different solution using java-11 or higher.
回答2:
You can use Collectors.toMap()
:
List<User> l = new ArrayList<> (list.stream()
.collect(Collectors.toMap(u -> u.name,
u -> new User (u.name,u.languages),
(u1, u2) -> new User(u1.name, u1.languages + ", " + u2.languages)))
.values());
来源:https://stackoverflow.com/questions/61927722/collectors-reducing-to-list