Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot resolve method stream() issue

I am currently learning about streams in java, but when i try to write some simple code like this

Map<String, Integer> map = new TreeMap<>();
       map.put("Tom", 5);
       map.put("Andrew", 6);
       map.put("Kim", 3);
       map.put("Milo", 2);

       map.stream();

it gives me java cannot resolve method stream() I am using Inttelij and coding in java 11 and I honestly don't know what is going on.

like image 476
sadurator Avatar asked Jan 27 '23 12:01

sadurator


1 Answers

According to the documentation:

Streams can be obtained in a number of ways. Some examples include:

  • From a Collection via the stream() and parallelStream() methods;
  • From an array via Arrays.stream(Object[]);
  • From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) or Stream.iterate(Object, UnaryOperator);
  • The lines of a file can be obtained from BufferedReader.lines();
  • Streams of file paths can be obtained from methods in Files;
  • Streams of random numbers can be obtained from Random.ints();
  • Numerous other stream-bearing methods in the JDK, including BitSet.stream(), Pattern.splitAsStream(java.lang.CharSequence), and JarFile.stream().

Since the Map doesn't implement Collection interface, it doesn't fit any of these ways and means doesn't have stream() method. But you could use stream with:

map.keySet().stream();
map.values().stream();
map.entrySet().stream();
like image 58
Ruslan Avatar answered Jan 29 '23 02:01

Ruslan