我遇到了麻烦com.googlecode.json-simple和Java-8流一起工作。
下面的代码是不工作:
JSONArray jsonArray = new JSONArray();
List<String> a = jsonArray.stream()
.map(o -> ((Map)o).get("s"))
.map(Object::toString)
.collect(Collectors.toList());
它说 :
java: incompatible types: java.lang.Object cannot be converted to java.util.List<java.lang.String>
但它应该工作,因为我明确的类型转换流对象String
,收集前。
由于JSONArray
延伸ArrayList
但不绑定类型吧,一个办法做到这一点可能会遍历在索引列表,而不是为:
JSONArray jsonArray = new JSONArray();
List<String> list = IntStream.range(0, jsonArray.size())
.mapToObj(i -> ((Map) jsonArray.get(i)).get("s"))
.map(Object::toString)
.collect(Collectors.toCollection(ArrayList::new));