java Failed to convert int array to Set using Collectors.toSet() [duplicate] - java

This question already has answers here:
Java stream - map and store array of int into Set
(3 answers)
How do I convert a Java 8 IntStream to a List?
(5 answers)
Arrays.asList() not working as it should?
(12 answers)
Closed 2 days ago.
i can't understand basic thing here i have :
int[] arr = {2,5,2,4,6,6,1,5,4};
Set<Integer> orederSet = new HashSet<Integer>(Arrays.stream(arr).collect(Collectors.toSet()));
side note :
also this not working :
Set<Integer> orederSet = new HashSet<Integer>(Arrays.asList(arr));
which gives me compile error :
java: 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.Set<java.lang.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
I dont understand what is wrong in my code ..

Your arr is an int[]. That means you're calling Arrays#stream(int[]), which returns an IntStream. But none of the primitive stream interfaces1 have a #collect(Collector) method. You have to convert the IntStream into a Stream<Integer>. The easiest way to do that is with the IntStream#boxed() method.
int[] arr = {2, 5, 2, 4, 6, 6, 1, 5, 4};
Set<Integer> set =
Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toSet()); // Set<Integer>
As for why the following doesn't work:
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
That's due to Arrays.asList(arr) returning a List<int[]> rather than a List<Integer>.
Neither primitives nor arrays work especially well with generics. Arrays of primitives are worse. A primitive can at least be auto-boxed to the reference type (and vice versa, i.e., unboxed) when appropriate. But primitive arrays have no such special treatment.
1. The primitive stream interfaces include IntStream, LongStream, and DoubleStream.

Try to convert IntStream:
Set<Integer> orderSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());

Related

How to covert LinkedList<LinkedList<Integer>>to int[][] type using stream in Java 8? [duplicate]

This question already has an answer here:
How to collect the results of a Stream in a primitive array?
(1 answer)
Closed 7 months ago.
How can I convert a LinkedList<LinkedList<Integer>> to int[][] type?
I have created
LinkedList<LinkedList<Integer>> result = new LinkedList<LinkedList<Integer>>();
I want to convert the result to int[][] type using Java 8 functionality.
First of all, how would one convert a LinkedList<Integer> to an int[] using Streams?
This is done by streaming the values, converting the Stream<Integer> to an IntStream, and using its built-in toArray() method:
LinkedList<Integer> list = something;
int[] array = list.stream().mapToInt(i -> i).toArray()
Now that we can convert the inner list, what do we do about the outer list? We start by streaming it (as a Stream<LinkedList<Integer>>), converting the inner data using the above approach (thus making a Stream<int[]>), and then outputting that as an array:
LinkedList<LinkedList<Integer>> list = something;
int[][] array = list.stream()
.map(l -> l.stream().mapToInt(i -> i).toArray())
.toArray(int[][]::new);

incompatible types: inference variable T has incompatible bounds [duplicate]

This question already has answers here:
How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java
(5 answers)
Using Arrays.asList with int array
(2 answers)
Closed 8 years ago.
I have the following piece of code
public int solution(int X, int[] A) {
List<Integer> list = Arrays.asList(A);
For some reason it's throwing the following compilation error
Solution.java:11: error: incompatible types: inference variable T has
incompatible bounds
List list = Arrays.asList(A);
^
equality constraints: Integer
lower bounds: int[] where T is a type-variable:
T extends Object declared in method asList(T...)
I assume this a Java 8 feature, but I'm not sure how to resolve the error
Arrays.asList is expecting a variable number of Object. int is not an Object, but int[] is, thus Arrays.asList(A) will create a List<int[]> with just one element.
You can use IntStream.of(A).boxed().collect(Collectors.toList());
In Java 8 you can do
List<Integer> list = IntStream.of(a).boxed().collect(Collectors.toList());
There is no shortcut for converting from int[] to List as Arrays.asList does not deal with boxing and will just create a List which is not what you want. You have to make a utility method.
int[] ints = {1, 2, 3};
List<Integer> intList = new ArrayList<Integer>();
for (int index = 0; index < ints.length; index++)
{
intList.add(ints[index]);
}

Arrays.asList return type mismatch confusion [duplicate]

This question already has answers here:
Boxing with Arrays.asList()
(2 answers)
Closed 9 years ago.
Why does the following not return a list of integers?
int[] ints = new int[] { 1, 2, 3, 4, 5 };
List<Integer> intsList = Arrays.asList(ints); //compilation error
But instead a List of int[]
While this
String[] strings = new String[] { "Hello", "World" };
List<String> stringsList = Arrays.asList(strings);
Returns a list of String. I am guessing it fails due to it being an array of primitives but why? And how do I actually return a list of int.
It's because Arrays.asList(new int[] { 1, 2, 3, 4, 5 }) will create a List<int[]> with one item, not a List<Integer> with five items.
Note however that this would do what you expected:
List<Integer> intsList = Arrays.asList(1, 2, 3, 4, 5);
Your other alternatives are:
to create an Integer[] in the first place, or
to populate your list in a loop
The method is defined as:
public static <T> List<T> asList(T... a)
So in your first case, T is int[] and you are passing a single object to the method (i.e. the array), therefore it returns a list of int[].
I think you are mistaking with asList(1, 2, 3, 4, 5) (i.e. 5 items)
The T in List<T> must be some subtype of java.lang.Object, which int is not. THe only other interpretation is, as we are using ... that you are supplying an array of int[], i.e. an int[][]. So you get List<int[]>.
String is a subtype of Object, so this works as expected. Also the only way it can work prior to varargs introduction in J2SE 5.0. Generally the interpretation of existing code should not alter between language versions.
Now, if you wanted a List<Integer> you could go through and box each integer. If there a lot of these elements in your program then memory may be an issue. You may want to use a third-party library that compactly backs a List<Integer> with an int[], or just stick with arrays for primitives. It's unfortunate that Java does not support value types.

Trying to convert array of ints to a list

I'm trying to convert an array of type int to a List by doing
List<Integer> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);
but for some reason I keep getting an error saying
Type mismatch: cannot convert from List<int[]> to List<Integer>
I don't understand what the issue is.
I know doing
List<int[]> endingRoutesBusStopsList = Arrays.asList(endingRoutesBusStops);
will solve the error, but then I can't use it the way I want.
Anyone have any ideas?
This is caused by the fact that int[] is different from Integer[]. Autoboxing does not work on Arrays.
The issue is because an "int[]" is an Object,
Arrays.asList(T...) gets generic vararg, that it means it treats "int[]" as "Object" (the common superclass for array int[] and Integer is Object)
so that from asList method perspective you don't pass an array of ints, but you pass an object .
In any way you should make implicit convertion from int to wrapper Integer. It is advisable to make it explicitly.
We are missing some more of your code, but in general, let me try and answer with code:
This works:
Integer[] arrayOfInt = { Integer.valueOf(0), Integer.valueOf(1) };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
This works too because the primitive "1" is autoboxed to an Integer object:
Integer[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
Finally, this won't work because an int[] cannot be autoboxed to Integer[]:
int[] arrayOfInt = { 1, 2, 3, 4 };
List<Integer> listOfInt = Arrays.asList(arrayOfInt);
UPDATE: this comes from way down in the comments in a discussion with #MichaelBorek . This example repeatedly tries the same code either autoboxing or not. The cost of autoboxing seems to be that the code that uses it takes 5 times longer than the one that uses Objects directly.

Can I convert array of integer to List<int> or List<Integer> by Arrays.asList(array)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?
You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);
You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);
Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.
If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.

Categories

Resources