简体   繁体   English

Stream.flatMap() 从 char[] 到 Character stream

[英]Stream.flatMap() from char[] to Character stream

import java.util.*; 
import java.util.stream.*; 

class Playground { 

    public static void main(String[] args) 
    { 
        // Creating a character array 
        char arr[] = { '1', '2', '3', '4', '5' }; 

        // --------- Using Stream.of() --------- 
        // Will work efficiently 

        // to convert int array into Stream 
        Stream<char[]> stream = Stream.of(arr); 
        Stream<Integer> s = stream.flatMap((item)->new String(item).chars().mapToObj(a->(char)a));

        // Displaying elements in Stream 
        s.forEach(str -> System.out.print(str + " ")); 
    } 
} 

I'm trying to convert a char[] into a stream of Characters with flatMap() but I got the following error我正在尝试使用 flatMap() 将 char[] 转换为 stream 字符,但出现以下错误

./Playground/Playground.java:14: error: incompatible types: inference variable R has incompatible bounds
        Stream<Integer> s = stream.flatMap((item)->new String(item).chars().mapToObj(a->(char)a));
                                          ^
    equality constraints: Integer
    lower bounds: U,Character
  where R,T,U are type-variables:
    R extends Object declared in method <R>flatMap(Function<? super T,? extends Stream<? extends R>>)
    T extends Object declared in interface Stream
    U extends Object declared in method <U>mapToObj(IntFunction<? extends U>)
1 error

Need help with understanding the error and how to accomplish this task.在理解错误以及如何完成此任务方面需要帮助。 Specifically how this fix this line of code using flatMap() from char[] to Character stream.具体来说,这是如何使用 flatMap() 从 char[] 到 Character stream 修复这行代码的。

Stream<Integer> s = stream.flatMap((item)->new String(item).chars().mapToObj(a->(char)a))

Edit: So the problems turns out not to be about Stream but lambda expression and I twitched the line and messed the typing up after fixing the lambda expression by accident.编辑:所以问题不是关于 Stream,而是关于 lambda 表达式,我在意外修复 lambda 表达式后抽动了线条并弄乱了打字。 The original line was原来的线路是

Stream<Character> s = stream.flatMap(item->{new String(item).chars().mapToObj(a->(char)a);});

and the issue was missing return statement inside {}.问题是 {} 中缺少 return 语句。 Then I altered the line to然后我将行更改为

Stream<Integer> s = stream.flatMap((item)->new String(item).chars())

because I thought IntStream::mapToObj was causing troubles however I forgot the boxed() in the end and got another type error so I added back the IntStream::mapToObj and posted the question but forgot to change the Stream type back to Character.因为我认为 IntStream::mapToObj 造成了麻烦,但是我最后忘记了 boxed() 并得到了另一个类型错误,所以我添加了 IntStream::mapToObj 并发布了问题但忘记将 Stream 类型改回 Character。 I got confused but the fog is cleared now.Thanks for the good answers.我很困惑,但迷雾现在已经清除了。谢谢你的好答案。

You were almost there.你快到了。 Just replace Stream<Integer> to Stream<Character> , as you are casting to a char in your code.只需将Stream<Integer>替换为Stream<Character> ,因为您正在转换为代码中的char

However, the problem about your code is that you are unnecessarily flatMap ping .但是,关于您的代码的问题是您不必要地flatMap ping Stream.of expects an array with a reference type as its compound type. Stream.of需要一个以引用类型作为其复合类型的数组。 Further, Arrays.stream does not have an overload for char[] .此外, Arrays.stream没有char[]的重载。 You end up streaming over something that is guaranteed to be a single element.您最终流式传输保证是单个元素的内容。 That element is your char[] .该元素是您的char[]

You could just drop the flatMap operation, and directly convert the char array to a String.你可以放弃flatMap操作,直接将 char 数组转换为 String。

String str = new String(arr);
Stream<Character> characterStream = str.chars().mapToObj(c -> (char) c);

It's not clear what you are trying to achieve with this detour of unnecessary operations.目前尚不清楚您要通过这种不必要的操作绕行来实现什么。 When you want to stream over an array, just start with that operation, instead of creating a single element stream, to chain flatMap , to chain another map .当你想对数组进行 stream 时,只需从该操作开始,而不是创建单个元素 stream 来链接flatMap ,链接另一个map

Your code does already contain an approach for streaming over a char[] array, in the middle of the other operations, using the String constructor.您的代码确实已经包含一种使用String构造函数在其他操作中间流过char[]数组的方法。

char[] arr = { '1', '2', '3', '4', '5' };

new String(arr).chars().forEach(i -> System.out.print(i + " "));

This will print the Unicode numbers.这将打印 Unicode 数字。 When you want to print characters instead, just change the terminal operation:当你想改为打印字符时,只需更改终端操作:

new String(arr).chars().forEach(i -> System.out.print((char)i + " "));

or要么

new String(arr).chars().forEach(i -> System.out.printf("%c ", i));

You can also use您也可以使用

new String(arr).chars().mapToObj(i -> (char)i).forEach(i -> System.out.print(i+" "));

but this bears boxing overhead, as it creates a Stream<Character> .但这会产生装箱开销,因为它创建了一个Stream<Character>


Note that new String(arr) bears a copying overhead, as it creates an immutable object. You can avoid this by using请注意, new String(arr)会产生复制开销,因为它会创建一个不可变的 object。您可以通过使用来避免这种情况

CharBuffer.wrap(arr).chars().forEach(i -> System.out.printf("%c ", i));

Of course, you can insert as many curlicues as you want, eg当然,你可以插入任意多的花体,例如

Stream.of(arr)
    .flatMapToInt(array -> CharBuffer.wrap(array).chars())
    .mapToObj(i -> (char)i) // returns a Stream<Character> not Stream<Integer>
    .forEach(i -> System.out.printf("%c ", i));

but there is no reason to do so.但没有理由这样做。

  • You can use Arrays.stream() for any array except byte, char or short.您可以将Arrays.stream()用于除 byte、char 或 short 之外的任何数组。
  • You can use *Stream.of() for any primitive array of type * where * is Int or Double, or Long.您可以将*Stream.of()用于类型 * 的任何原始数组,其中 * 是 Int 或 Double,或 Long。
  • You can use Stream.of() for any Object array.您可以对任何 Object 数组使用Stream.of()

All of the following work as explained above.以下所有工作如上所述。

Integer[] IntegerArray = {1,2,3,4};
Arrays.stream(IntegerArray).forEach(System.out::println);
Stream.of(IntegerArray).forEach(System.out::println);

int[] intArray = {1,2,3,4};
Arrays.stream(intArray).forEach(System.out::println);
IntStream.of(intArray).forEach(System.out::println);

double[] doubleArray = {1.2,3.3,4.5,6.7};
Arrays.stream(doubleArray).forEach(System.out::println);
DoubleStream.of(doubleArray).forEach(System.out::println);

String[] stringArray = {"a","b","c","d"};
Stream.of(stringArray).forEach(System.out::println);

To solve your actual problem, try this.要解决您的实际问题,请尝试此操作。

     // Creating a character array 
        char arr[] = { '1', '2', '3', '4', '5' }; 

        // --------- Using Stream.of() --------- 
        // Will work efficiently 

        // to convert int array into Stream 
        Stream<char[]> stream = Stream.of(arr); 


        // Displaying elements in Stream 
        s.forEach(str -> System.out.print(str + " ")); 
        Stream<Integer> s = stream.flatMapToInt((item)->(new String(item)).chars()).boxed();
        //or
        IntStream s = stream.flatMapToInt((item)->(new String(item)).chars());

        // Displaying elements in Stream 
        s.forEach(str -> System.out.print((char)str + " ")); 



You have used Stream<Integer> instead of Stream<Character> .您使用Stream<Integer>而不是Stream<Character> If you want to use Stream<Integer> , you need to use IntStream::boxed or mapToObj(a -> Integer.valueOf(a)) as shown below:如果要使用Stream<Integer> ,则需要使用IntStream::boxedmapToObj(a -> Integer.valueOf(a)) ,如下所示:

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        char arr[] = { '1', '2', '3', '4', '5' };

        Stream<char[]> stream1 = Stream.of(arr);
        Stream<Character> chars = stream1.flatMap(item -> new String(item).chars().mapToObj(a -> (char) a));
        chars.forEach(c -> System.out.print(c + " "));

        System.out.println();

        Stream<char[]> stream2 = Stream.of(arr);
        Stream<Integer> ints = stream2.flatMap(item -> new String(item).chars().boxed());
        ints.forEach(i -> System.out.print(i + " "));

        System.out.println();

        Stream<char[]> stream3 = Stream.of(arr);
        Stream<Integer> integers = stream3.flatMap(item -> new String(item).chars().mapToObj(a -> Integer.valueOf(a)));
        integers.forEach(i -> System.out.print(i + " "));
    }
}

Output: Output:

1 2 3 4 5 
49 50 51 52 53 
49 50 51 52 53 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM