如何使用Java Streams从HashMap的ArrayList中提取字符串
Using Java Streams to Extract
optValue from ArrayList<HashMap<String, String>> Great question! Converting your existing loop to Java Streams is a clean, concise way to achieve the same result. Here's the equivalent stream-based implementation:
import java.util.stream.Collectors; // ... List<String> values = optMapList.stream() .map(entry -> entry.get("optValue")) .collect(Collectors.toList());
Let's break down what each part does:
optMapList.stream(): Converts yourArrayListinto aStream<HashMap<String, String>>, enabling stream operations on the collection..map(entry -> entry.get("optValue")): Transforms eachHashMapin the stream into its correspondingoptValuestring—this is exactly what your original loop does withentry.get("optValue")..collect(Collectors.toList()): Gathers all the transformed strings into a newList<String>, mirroring the behavior of your originalvalues.add(...)loop.
Additional Notes:
- Null handling: Just like your original code, if any
HashMaplacks the"optValue"key,entry.get("optValue")will returnnull, which will be included in the resulting list. To exclude null values, add a.filter(Objects::nonNull)step right after themapoperation. - Java 16+ shortcut: If you're using Java 16 or later, you can simplify the collection step with the built-in
Stream.toList()method, which returns an immutable list:
Note that this immutable list can't be modified (unlike the mutableList<String> values = optMapList.stream() .map(entry -> entry.get("optValue")) .toList();ArrayListtypically returned byCollectors.toList()).
内容的提问来源于stack exchange,提问作者Prateek Narendra
相关产品推荐
相关产品推荐

