0

I am launching in java some SQL queries, which will return some data that looks like :

[ID,Description,WhateverColumn,...,...,ImportantNumber]

Sample:

[1,"Desc",...,...,1]

[1,"Desc",...,...,2]

[1,"Desc",...,...,3]

[2,"Desc",...,...,1]

[3,"Desc",...,...,3]

[3,"Desc",...,...,5]

I am using the following List to store it in memory:

List<Object[]> myList = queryLaunched(...);

Later on, I want to do some operations with this List of Object[]:

[[1,"Desc",...,...,1],[1,"Desc",...,...,2],...]

and I am trying to use stream.map in the following way:

myList.stream().map(item -> System.out.println(item.toString()));

but I just receive this error:

Type mismatch: cannot convert from Stream<Object> to void

Wherever I look in google I just find samples made with List<Class>, not with List<Object[]>.

How could I print, and therefore, after it, start doing operations with each of the items in that list?

Mayday
  • 4,680
  • 5
  • 24
  • 58
  • 1
    I am sorry Tom, I agree with you. When i posted the question I was sure I had to use map, and Eran made me see why I shouldn't do that. But now I see it is correctly answered in that question what I was trying to do. Thank you – Mayday Aug 31 '16 at 08:25

1 Answers1

5

map is used to transform a Stream<TypeA> to a Stream<TypeB>. In order to print the elements, don't use map.

You can use a terminal operation :

myList.stream().forEach(item -> System.out.println(Arrays.toString(item)));

or an intermediate operation (which can be followed by additional operations) :

myList.stream().peek(item -> System.out.println(Arrays.toString(item)))... ;

Since your elements are arrays, you should print them with System.out.println(Arrays.toString(item)).

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Or without lambdas: `myList.stream().map(Arrays::toString).forEach(System.out::println);` – 4castle Aug 31 '16 at 07:46
  • Hmmm, answer looks pretty cool. I must be missing something though: When I use your option with forEach it prints all the elements in the array perfectly. However, If i substitute "forEach" for "peek" it doesnt seem to be doing anything. Do I need to do any extra thing? – Mayday Aug 31 '16 at 07:52
  • @Mayday `peek` is an intermediate operation, so it will only be executed if you have some terminal operation after it (such as `collect`, `reduce`, `forEach`, etc...). Besides that, it may not be executed for all the elements of the stream (it will only be executed for elements which were required for executing the terminal operation). – Eran Aug 31 '16 at 07:54
  • Alright, that explains it. Sorry, I am still trying to learn these new concepts on Java SE 8. Thank you very much for your answers, were really helpfull :) – Mayday Aug 31 '16 at 07:55