2016-07-12 4 views
4

私はintストリームを持ち、そのストリームの各要素がいくつかの計算を行い、それらをMapとして返すことを望んでいます。ここで、キーはint値であり、値はその計算の結果です。int streamをマップに変換する

IntStream.range(0,10).collect(Collectors.toMap(Function.identity(), i -> computeSmth(i))); 

computeSmth(Integer a):私は、次のコードを書きました。次のコンパイラエラーが発生する

method collect in interface java.util.stream.IntStream cannot be applied to given types; 
    required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R> 
    found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.String>> 
    reason: cannot infer type-variable(s) R 
    (actual and formal argument lists differ in length) 

私は間違っていますか?

+6

'IntStream'はわずか3引数' collect'を持っています。あなたは、 '' toMap'を3書式の書式で書き直すか、 '' Intream'を '.boxed()'で 'Stream 'に変換する必要があります。 – Misha

+0

@Mishaありがとう、ちょうど 'boxed()'について学びました。確かに 'mapToObj(Integer :: valueOf)'よりも改善されています。 :-) –

答えて

4

ここは自分のコードですが、それはあなたのために働くでしょう。

関数リファレンスバージョン

public class AppLauncher { 

public static void main(String a[]){ 
    Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),AppLauncher::computeSmth)); 
    System.out.println(map); 
} 
    public static Integer computeSmth(Integer i){ 
    return i*i; 
    } 
} 

ラムダ式バージョン

public class AppLauncher { 

    public static void main(String a[]){ 
     Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),i->i*i)); 
     System.out.println(map); 
    } 
} 
+0

確かに '.boxed()'が成功の鍵でした! – user1075613

関連する問題