Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用Guava函数将List转换为List_Java_Guava - Fatal编程技术网

Java 使用Guava函数将List转换为List

Java 使用Guava函数将List转换为List,java,guava,Java,Guava,如何使用Guava函数将下面的一个列表字符串值列表转换为一个整数列表 List<String> list1 = ImmutableList.of("1", "2"); List<String> list2 = ImmutableList.of("3", "4"); List<String> list3 = ImmutableList.of("5", "6"); List<List<String>> lists = ImmutableLi

如何使用Guava函数将下面的一个列表字符串值列表转换为一个整数列表

List<String> list1 = ImmutableList.of("1", "2");
List<String> list2 = ImmutableList.of("3", "4");
List<String> list3 = ImmutableList.of("5", "6");
List<List<String>> lists = ImmutableList.of(list1, list2, list3);
这就是我要做的,而不是使用foreach:

`List<Integer> ints = new ArrayList<Integer>();
  for (List<String> list : lists) {
   for (String string : list) {
    Integer integer = Integer.valueOf(string);
    ints.add(integer);
    }
 }`
一旦具备了该功能,就可以在一行中将字符串列表转换为整数列表:

List<String> stringList = getMyStrings();
List<Integer> intList = Lists.transform(stringList, StringToIntegerAdapter.INSTANCE);
一旦具备了该功能,就可以在一行中将字符串列表转换为整数列表:

List<String> stringList = getMyStrings();
List<Integer> intList = Lists.transform(stringList, StringToIntegerAdapter.INSTANCE);

使用@Jim的StringToIntegerAdapter,您可以在Guava中使用以下方法紧凑地执行所需的转换:

List<List<String>> strings = getString();
List<Integer> intList = Lists.newArrayList(Iterables.transform(
    Iterables.concat(strings), StringToIntegerAdapter.INSTANCE);

使用@Jim的StringToIntegerAdapter,您可以在Guava中使用以下方法紧凑地执行所需的转换:

List<List<String>> strings = getString();
List<Integer> intList = Lists.newArrayList(Iterables.transform(
    Iterables.concat(strings), StringToIntegerAdapter.INSTANCE);

使用传统的for-each有什么错?使用传统的for-each有什么错?Paul-关于你的问题,为什么不使用传统的for/each-一旦你为你最常见的需求建立了一套适配器,这样的适配器就很方便了。如上面的示例所示,转换整个集合只需要一行简洁的代码,而不是每行多行代码。这是一个好的开始,但是Iterators.transform需要并返回一个迭代器,而不是列表。此外,您的代码将列表转换为列表,但OP希望将列表转换为列表,将列表列表转换为单个串联列表。Iterables.transform而不是迭代器。transform.Doh!谢谢你的鹰眼。我将调整答案。非常感谢。Paul-关于你的问题,为什么不使用传统的for/each-一旦你为你最常见的需求构建了一套适配器,这样的适配器就很方便了。如上面的示例所示,转换整个集合只需要一行简洁的代码,而不是每行多行代码。这是一个好的开始,但是Iterators.transform需要并返回一个迭代器,而不是列表。此外,您的代码将列表转换为列表,但OP希望将列表转换为列表,将列表列表转换为单个串联列表。Iterables.transform而不是迭代器。transform.Doh!谢谢你的鹰眼。我将调整答案。非常感谢。