我需要使用Google将数组放入JSON对象中。
JSONObject jsonObject = new JSONObject();
State[] states = getStates();
for(State currentState: states) {
jsonObject.put(String.valueOf(currentState.getId()), currentState.getName());
}我试过使用Iterables.transform,但这是行不通的。
Iterables.transform(states, new Function<State, JSONObject>() {
@Override
public JSONObject apply(State currentState) {
return jsonObject.put(String.valueOf(currentState.getId()), currentState.getName());
}
});怎么了?
发布于 2014-12-08 16:48:39
你真的需要用这种方式来实现它吗?这不是Iterables.transform()设计的目的。
首先,Iterables.transform()不接受数组作为其第一个参数。您必须将states封装到任何Iterable中。最简单也是最好的方法是Arrays.asList(states)。其次,Iterables.transform()方法的思想是使用映射函数创建转换后的序列,而不仅仅是迭代。我不推荐以下内容,但是您可以将Function参数化为<State, Void>,并返回null来模拟每个语义。第三,您必须迭代Iterables.transform的结果,因为这个函数很懒,在使用热切的for或其他急切的东西开始迭代之前什么也不做。第四,只要新创建的迭代不被复制到任何集合(通过语义,即复制到List<T>实例),对该迭代的任何重新迭代都会导致每次隐式为该迭代(即从for- each )调用iterator.next()时再进行一次转换。因此:
final JSONObject jsonObject = ...
// ...
final Iterable<Void> voids = Iterables.transform(Arrays.asList(states), new Function<State, Void>() {
@Override
public Void apply(State currentState) {
jsonObject.put(String.valueOf(currentState.getId()), currentState.getName());
return null;
}
});
for ( final Void v : voids ) {
// do nothing
}这真是个又坏又丑的主意。您确实需要一个创建/提供JSON对象的聚合函数,一个要迭代的State元素序列,以及一个接受累积的JSON对象和单个state对象并返回更新的JSON对象的双函数。类似于它的通用形式(您可以创建自己的函数和装饰器):
public static <T, R> R reduce(Supplier<R> init, Iterable<T> sequence, BiFunction<R, T, R> function) {
R accumulator = init.get();
for ( final T item : sequence ) {
accumulator = function.apply(accumulator, item);
}
return accumulator;
}https://stackoverflow.com/questions/27362020
复制相似问题