Problem with java 8 builders Type of mismatch: cannot convert from list <Object> to list <String>

I had working code with an earlier version of java 8 that I used to get unique values ​​from a list, but since I upgraded to JDK 66, it gave me an error

Type mismatch: cannot convert from List<Object> to List<String>

 List<String> instList = new ArrayList<String>(); while (res.next()) { instList.add(res.getString("INST").toString()); } List<String> instListF = instList.stream().distinct().collect(Collectors.toList()); 

Where res is the result that I get from the database, not sure what is wrong, but an idea?

+12
source share
3 answers

Well, I also recently encountered a similar error Type mismatch: cannot convert from Set<Object> to Set<String> . The following is snippet- code:

 public static void main(String[] args) { String[] arr = new String[]{"i", "came", "i", "saw", "i", "left"}; Set<String> set = Arrays.asList(arr).stream().collect(Collectors.toSet()); System.out.println(set.size() + " distinct words: " + set); } 

Here is a screenshot for reference-: enter image description here

Now let me explain why I got this error? In my case, the code displayed a compile-time error, because there was a mismatch in the compiler version in the project properties. I chose 1.7 , but it should be 1.8 , since this feature was added in 1.8 .

enter image description here

Therefore, please write down points- below:

  1. The appropriate JDK was selected in the Java build path . for example JDK 1.8 in this case.
  2. The appropriate version of the compiler should be selected in the Java Compiler section (as shown in the screenshot above) in the project properties. e.g. 1.8

I hope this helps you.

+8
source

I checked the following complete example:

 import java.sql.ResultSet; import java.sql.SQLException; import java.util.stream.Collectors; import java.util.List; import java.util.ArrayList; public class Test { public List<String> test(ResultSet res) throws SQLException { List<String> instList = new ArrayList<String>(); while (res.next()) { instList.add(res.getString("INST").toString()); } List<String> instListF = instList.stream().distinct().collect(Collectors.toList()); return instListF; } } 

It compiles fine with javac 8u25, 8u40, 8u60, 8u71 (note that 8u71 is an 8u66 security update, so essentially the same thing). Try to clean the project and restore it from scratch.

+4
source

After checking my compiler level (according to Ashish above), I realized that I have neither a data type in either the list or the set. As soon as I added, it worked.

 List<Integer> number = Arrays.asList(2, 3, 4, 5, 3); Set<Integer> square = number.stream() .map(x -> x * x) .collect(Collectors.toSet()); 
0
source

All Articles