我有一个有效载荷,它返回以下 ArrayList
:
[0] true (boolean)
[1] "someStringValue"
我需要使用 lambda 表达式 提取包含 String
值的元素的值。
有什么想法吗?
最佳答案
首先请注意,您没有指定您的 ArrayList
是什么持有。我假设它是 Object
.但是,如果它是某个容器类,那么您需要在这里和那里稍微调整一下代码。应该比较容易。如果您遇到困难,请不要费心发表评论和提供其他信息。
没有 Java 8
让我们先来看看如果没有 Streams 或 Lambda,你会怎么做:
ArrayList<Object> list = ...
List<String> result = new ArrayList<>();
// Iterate all elements
for (Object obj : list) {
// Ignore elements that are not of type String
if (!(obj instanceof String)) {
continue;
}
// The element is String, cast it
String objAsText = (String) obj;
// Collect it
result.add(objAsText);
}
列表result
现在只包含原始列表的真实类型 为String
的元素.
使用 Java 8(流、Lambda、方法引用)
我们现在可以使用 Stream API 轻松编写等效版本。请注意,您可能会混淆 Stream
s 通常与 Lambda(它们是不同的技术,尽管 Lambda 经常用于 Stream-API)。
ArrayList<Object> list = ...
result = list.stream() // Stream<Object>
.filter(String.class::isInstance) // Stream<Object>
.map(String.class::cast) // Stream<String>
.collect(Collectors.toList());
就是这样,非常简单易读。 Collection#stream
( documentation ) 返回 Stream
由给定集合中的元素组成。 Stream#filter
( documentation ) 方法返回 Stream
跳过不符合条件的元素。 Stream#map
( documentation ) 转换 Stream<X>
进入Stream<Y>
通过将给定的方法应用于所有对象( X
可以等于 Y
)。最后 Stream#collect
( documentation ) 方法使用给定的 Collector
收集所有元素.
如果您真的想使用 Lambdas,那么这可能更符合您的需要:
ArrayList<Object> list = ...
List<String> result = new ArrayList<>();
list.forEach(obj -> { // This is a big lambda
// Ignore elements that are not of type String
if (!(obj instanceof String)) {
return;
}
// The element is String, cast it
String objAsText = (String) obj;
// Collect it
result.add(objAsText);
});
但我真的认为你混淆了这里的术语。
关于java - 使用 lambda 表达式从 ArrayList<E> 获取字符串元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47579963/