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 + " "));
}
}
char []をflatMap()で文字のストリームに変換しようとしていますが、次のエラーが発生しました
./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
エラーとこのタスクを実行する方法を理解するのに助けが必要です。具体的には、char []からCharacterストリームへのflatMap()を使用してこのコード行を修正する方法。
Stream<Integer> s = stream.flatMap((item)->new String(item).chars().mapToObj(a->(char)a))
編集:問題はストリームではなくラムダ式に関するものであることが判明し、私は誤ってラムダ式を修正した後、線をひねって入力を混乱させました。元の行は
Stream<Character> s = stream.flatMap(item->{new String(item).chars().mapToObj(a->(char)a);});
問題は、{}内のreturnステートメントが欠落していたことです。次に、行を
Stream<Integer> s = stream.flatMap((item)->new String(item).chars())
IntStream :: mapToObjが問題を引き起こしていると思ったので、最後にboxed()を忘れて別のタイプエラーが発生したため、IntStream :: mapToObjを追加して質問を投稿しましたが、StreamタイプをCharacterに戻すのを忘れていました。私は混乱しましたが、霧は今晴れています。良い答えをありがとう。
のStream<Integer>
代わりに使用しましたStream<Character>
。を使用する場合はStream<Integer>
、IntStream :: boxedまたはmapToObj(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 + " "));
}
}
出力:
1 2 3 4 5
49 50 51 52 53
49 50 51 52 53
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加