如何使用Java Lambda将列表元素收集为新类型对象列表?
Got it, let's work through this. You’ve already got the hang of using Collectors.groupingBy to get a Map<String, List<String>>, but you want to wrap that grouped data into a list of custom objects so it’s easier to reuse across multiple functions—smart move, that’ll make your code cleaner and more type-safe.
Step 1: Define your target object
First, create a simple POJO to hold the grouped data. Let’s say you want each group to have a key/name and a list of the relevant values from your RowData. For example:
public class GroupedResult { private String groupKey; private List<String> values; // Constructor, getters, (optional) setters and toString public GroupedResult(String groupKey, List<String> values) { this.groupKey = groupKey; this.values = values; } // Add getters for groupKey and values here public String getGroupKey() { return groupKey; } public List<String> getValues() { return values; } }
Step 2: Convert from Map to List of custom objects
Now, take your existing grouping logic, then transform the resulting Map into a list of GroupedResult objects. Here’s how to do it in one smooth pipeline:
Assuming your RowData has a method like getGroupIdentifier() to get the grouping key, and getRelevantValue() to get the value you want to collect:
List<RowData> rowDataList = // your source list of RowData List<GroupedResult> groupedResults = rowDataList.stream() // First, group into the Map you already know how to make .collect(Collectors.groupingBy( RowData::getGroupIdentifier, Collectors.mapping(RowData::getRelevantValue, Collectors.toList()) )) // Now convert each Map entry to a GroupedResult .entrySet() .stream() .map(entry -> new GroupedResult(entry.getKey(), entry.getValue())) // Collect into the final list .collect(Collectors.toList());
How this works:
- The first
collectdoes the heavy lifting of grouping yourRowDatainto aMap<String, List<String>>, just like you were doing before. - We then call
entrySet().stream()to turn the map’s key-value pairs into a stream. - Each entry is mapped to a new
GroupedResultobject, using the entry’s key as the group key and the entry’s value list as the values. - Finally, we collect all those
GroupedResultinstances into a list that’s ready to pass around to your other functions.
Extra tips:
- If you need to sort the groups, add a
.sorted(Comparator.comparing(GroupedResult::getGroupKey))after themapstep before collecting to list. - If you want to handle empty groups or filter out groups with no values, add a
.filter(entry -> !entry.getValue().isEmpty())right afterentrySet().stream(). - If your
RowDatahas more fields you want to include in the grouped object, just update theGroupedResultclass and adjust themapstep to pull in those extra values.
内容的提问来源于stack exchange,提问作者Cuga

