issue with java 8 collectors Type mismatch: cannot convert from List<Object> to List<String>
Well I have also faced similar kind of error Type mismatch: cannot convert from Set<Object> to Set<String>
recently. Below is the code snippet-:
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 the screen shot for reference-:
Now let me explain why was I getting this error? In my case code was displaying compile time error because there was mismatch in compiler version in project properties. I had selected 1.7 but it should be 1.8 since this feature has been added in 1.8.
So please make a note of below points-:
- Appropriate JDK has been selected in Java Build Path. e.g. JDK 1.8 in this case.
- Appropriate compiler version must be selected under Java Compiler (as displayed in above screenshot) in project properties. e.g. 1.8
I hope this would help you.
Java 8 Stream: type mismatch cannot conver stream object ot list object
You will have to change the statement from
List<Person> sList = customers.stream().sorted();
to
List<Person> sList = customers.stream().sorted().collect(Collectors.toList());
sorted
returns stream instance which further allows performing additional operations like filter. Hence as per streams API, if you wish to grab the list instance, you should do so by calling collect
method.
Java 8 - Type mismatch: cannot convert from List<Serializable> to List<String>
This is an Eclipse bug
Bug 508834, thanks to @Tunaki
Notice the method signatures:
//Stream.of
<T> Stream<T> of(T... values)
//Arrays.stream
<T> Stream<T> stream(T[] array)
Now, for Arrays.stream
it is obvious that a call with an array of type T
will return a Stream<T>
. But with Stream.of
should it return Stream<T>
or Stream<T[]>
? i.e. what is the type of the varags; are you passing your array are the first parameter (so the varargs are an array of arrays) or are you passing your array as all the parameters?
That's your issue.
ERROR: Type mismatch: cannot convert from Map<Object,List<Object>> to Map<String,List<>>
The following code does the same thing as your code but splits up the collect in to multiple map steps, this may work better for you:
Pattern splitPattern = Pattern.compile("\\|");
Map<String, List<Leader>> result =
vals.stream()
.map(splitPattern::split)
.map(leaderArgs -> new Leader(leaderArgs[0], leaderArgs[1], leaderArgs[2], leaderArgs[3]))
.collect(Collectors.groupingBy(leader -> leader.country));
I have also used Pattern
which will be a bit faster than repeated calls to String.split.
Simple XML output for this might be:
result.entrySet()
.forEach(entry -> {
System.out.println("<LeaderList country=\"" + entry.getKey() + "\">");
entry.getValue()
.forEach(leader -> System.out.println("<Leader name=\"" + leader.name + "\" age=\"" + leader.age + "\" sex=\"" + leader.sex + "\">"));
System.out.println("</LeaderList>");
});
The collect code is assuming the input vals
is a stream of String with one entry per line. For example to read a file:
Path path = ... file path
try (Stream<String> vals = Files.lines(path))
{
... the collect code
}
catch (final IOException ex)
{
// TODO error handling
}
Note: It is important to use a try-with-resources block with Files.lines
so that the stream is closed properly.
How to solve this error "Type mismatch: cannot convert from List<String> to Iterator<String>"
You should have specified that you are using at least version 2.0
where FlatMapFunction::call
returns actually an Iterator
and not Iterable
(in 1.6 this is the case for example). Thus, your rddX.flatMap
is suppose to return an Iterator<String>
, while Arrays.asList(e.split(" "))
returns a List<String>
.
But there is List::iterator
that you can use, as :
rddX.flatMap(e -> Arrays.asList(e.split(" ")).iterator())
Java Stream - Compile time Error - Type mismatch: cannot convert from Map<Object,Object> to Map<Integer,List<String>>
you need to make a slight change as split returns a String [].
np -> Arrays.asList(np.getAppsReceived().split(","))
Error : Type mismatch: cannot convert from List<Integer> to ArrayList<Integer>
The list
variable is a List<Integer>[]
, which means that any type of List
(ArrayList
, LinkedList
, etc.) could be stored in it. When retrieving an element from this list, all the Java compiler knows is that it's some type of List
; it doesn't know the specific type of List
(even though you as the programmer know that you're only storing ArrayList
items in the array). Therefore, ArrayList<Integer> l = list[a]
is a compilation failure because the compiler can't guarantee that the element retrieved from the array is an ArrayList
and not a different List
type.
There are a few ways to address this issue. Assuming you wanted to keep list
as an array, the most idiomatic approach would be to change its type to List<Integer>[]
instead of ArrayList<Integer>[]
. Since you are not using any methods or other API specific to ArrayList
, the List
interface is a better choice for this type.
public static void solve(int a) {
visited[a] = true;
List<Integer> l = list[a];
}
Another, less idiomatic approach would be to change the type of the list
variable from List<Integer>[]
to ArrayList<Integer>[]
. This change would cause your variable assignment to work as already written.
public class DFTList {
static ArrayList<Integer>[] list;
...
}
The final approach you could use when you have an array of the interface type (List<Integer>
in this case) would be to cast the element to the concrete type when storing it to the variable. This is basically telling the compiler that you as the developer know the element is of that subtype, so even though it cannot guarantee the assignment, it will allow it to happen. This approach defers the type checking — ensuring the List
is the ArrayList
subtype — until the code is actually run (at runtime). If the stored element is a subtype other than ArrayList
when the code is run (e.g. if it's a LinkedList
), then Java will throw a ClassCastException since the assignment to ArrayList
cannot happen.
Casting like this is not ideal, as it removes guarantees by the compiler that all types being used are guaranteed to be valid at runtime. However, there are times where it is necessary and appropriate.
public static void solve(int a) {
visited[a] = true;
ArrayList<Integer> l = (ArrayList<Integer>) list[a];
}
java - Stream collect toMap - Type mismatch
You have a compilation error: Cannot make a static reference to the non-static method indexOf(Object) from the type List
.
If you correct it as below, it will compile:
return strs.stream().collect(Collectors.toMap(coll -> strs.indexOf(coll), v -> v));
Or, using a method reference:
return strs.stream().collect(Collectors.toMap(strs::indexOf, v -> v));
Related Topics
Spring Boot JPA Unknown Column in Field List
Junit 5 - No Parameterresolver Registered for Parameter
Check If One List Contains Element from the Other
Java.Exe Finished With Non-Zero Exit Value 1
Convert String With Dot or Comma to Float Number
Regex to Match Substring After Nth Occurence of Pipe Character
Tomcat Server Error - Port 8080 Already in Use
Java 8 Convert Utc Time to Edt/Est So That Date Remains the Same
Checking If a Document Exists in a Firestore Collection
Regex to Match a String Not Starting or Ending With a Pattern
How to Write a User Input Based Constructor
Reading a Resource File from Within Jar
Selenium Webdriver: Modifying Navigator.Webdriver Flag to Prevent Selenium Detection
Httpclienterrorexception 400 Null Using Resttemplate in Microservices
No Content to Map Due to End-Of-Input Jackson Parser
How to Run Java Program in Terminal With External Library Jar