Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IntStream to Map

Tags:

I have an IntStream and want for each element of that stream to do some calculations and return them as Map where keys are int values and values are result of that computations. I wrote following piece of code:

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

where computeSmth(Integer a). I got next compiler error

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) 

What I'm doing wrong?

like image 763
maks Avatar asked Jul 12 '16 00:07

maks


People also ask

How do I collect a Stream map?

Method 1: Using Collectors.toMap() Function The Collectors. toMap() method takes two parameters as the input: KeyMapper: This function is used for extracting keys of the Map from stream value. ValueMapper: This function used for extracting the values of the map for the given key.

Can we create Stream of map?

Converting complete Map<Key, Value> into Stream: This can be done with the help of Map. entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.

How does IntStream range () work?

range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream. range(1,5) generates a stream of ' 1,2,3,4 ' of type int .

What is IntStream of in Java?

An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.


1 Answers

Here is my code, it will work for you.

Function Reference version

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;   } } 

Lambda expression version

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);     } } 
like image 195
Noor Nawaz Avatar answered Sep 23 '22 18:09

Noor Nawaz