Convert generic arraylist to non-generic using Java 8 Stream - java

I have some old code I'm trying to streamline:
ArrayList arr = (generic arraylist)
int[] newArr = new int[arr.size()];
for(int i=0; i<arr.size(); i++){
newArr[i]=(int)arr.get(i);
}
I want to use the Java Stream API to simplify this. Here is my attempt:
ArrayList arr = (generic arraylist)
List<Integer> = arr.stream().map(m -> (int)m).collect(Collectors.toList());
My understanding is that it would iterate through arr, typecast every object m to an int, and then collect it into a List. But my compiler says that the right-hand-side of the second line returns and Object and not a List. Where am I going wrong?

Per your attempt, it looks like you want to map your ArrayList to an ArrayList<Integer>. The good news is, you don't need to do any of this. The runtime type of ArrayList<Integer> is just ArrayList (this is called type erasure if you want to search for information about it). Only the compiler knows about the parameterized type.
So this code does what you want:
import java.util.ArrayList;
public class Cast {
public static void main(String[] args) {
// This represents the ArrayList of Integer in your existing code
ArrayList raw = new ArrayList(java.util.Arrays.asList(
Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3)
));
// You know what it is, so all you need to do is cast
ArrayList<Integer> typed = (ArrayList<Integer>)raw;
// Still works; now recognized as list of integer
for (Integer x : typed) {
System.err.println(x);
}
}
}

Related

Converting a List to an Array in Java

I am a List of Long type and would like to convert it to an array of long type.
However when adding elements to the list, it says it is unable to find method "add(int)"
my code looks like below
package collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class ListToArray {
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788);
list.add(1245898);
long[] arr=new long[list.size()];
arr=list.toArray();
}
}
Error I am getting are
Error(16,13): cannot find method add(int).
Error(21,25): incompatible types
Can someone point out where it's going wrong.
As suggested in the comments, you should add L to force the value to be a long:
list.add(121145788L);
list.add(1245898L);
Explanation:
the values you wanted to add are ints, and list is for longs. Adding the L makes the compiler use the number literal as a value of type Long explicitly, and that can be added to the list.
Without it, the numbers are treated as Integers, and those can't be added to a list of type Long, hence
cannot find method add(int)
There is a method add(long), and that's what is used when the L is used.
To convert to an array, you need to do it the old fashioned way:
for (int i = 0; i < arr.length; i++) {
arr[i]=list.get(i);
}
This is because long is a primitive, and Long is a reference type (i.e. it is an Object). Casting from primitives to Objects isn't always easy. In this case, the old fashioned way works well.
First, this is your code but with all the fixes!
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788L);
list.add(1245898L);
Long[] arr = new Long[list.size()];
list.toArray(arr);
}
And here is some explanation:
you have a list of type Long. When you add() items to the list - compiler expects them to be of type Long, but you are adding literal values (plain numbers like 121145788) so those are treated as integers (type int) and are autoboxed to Integer instead of Long. So add L to treat literals as long and then they are autoboxed into Long. Fine for the compiler :)
list.toArray(arr); this is the correct method to kinda convert a list to an array. Because the method you used returns array of Object and arr you created is not an array of Object.
And again this correct method I used takes T[] as input, so you need to change your arr declaration a bit to make it of type Long instead of an array of primitive type long.
If for some reason you need long[], the easiest way would be:
long[] arr = new long[list.size()];
for (int i=0; i < list.size(); i++) {
arr[i] = list.get(i);
}
Error(16,13): cannot find method add(int), this is because you are passing int instead of a Long value in a list of Long. You should be doing:
list.add(121145788l);
And for the second error follow this.Hope,it helps!
JVM doesn't automatically cast int (short, byte, char) to Long. It's explained on the next link.
Java: Why can't I cast int to Long
Converting List<Long> to long[] is possible and also is answered on SO.
How to convert List<Integer> to int[] in Java?
That's the answers:
using Java 8 streams
long[] arr = list.stream().mapToLong(Long::longValue).toArray();
using Guava
long[] arr = Longs.toArray(list);
using Apache Commons Lang
long[] arr = ArrayUtils.toPrimitive(list.toArray(new Long[0]))

java.lang.ClassCastException:[I cannot be cast to java.lang.Integer

public class Solution {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int l1=Integer.parseInt(br.readLine());int count=0;
String l2=br.readLine();
String[] a=l2.split(" ");int[] no=new int[l1];
for (int i=0;i<l1;i++) {
no[i]=Integer.parseInt(a[i]);
}
List list=Arrays.asList(no);
Set<Integer> set=new LinkedHashSet<Integer>(list);
***for (int integer : set) {***
count=Math.max(count, Collections.frequency(list, integer));
}
}
}
I get java.lang.ClassCastException:
[I cannot be cast to java.lang.Integer at Solution.main(Solution.java:23) at the highlighted part of the code. What is the reason for this?
You are trying to initialize a set from an array of primitive integers. When you do this
List list=Arrays.asList(no);
since List is untyped, you construct a list of integer arrays; this is definitely not what you are looking for, because you need List<Integer>.
Fortunately, this is very easy to fix: change declaration of no to
Integer[] no=new Integer[l1];
and construct list as follows:
List<Integer> list = Arrays.asList(no);
Everything else should work fine.
Set<Integer> set=new LinkedHashSet<Integer>(list); produce unchecked warnings. This masks that the correct generic type of list is List<int[]>, so set contains not Integers as intended, but arrays of ints. That's what is reported by ClassCastException: int[] (referred as [I) cannot be cast to Integer.
The simplest way to fix this code is to declare no as Integer[], not int[]. In this case, Arrays.asList will return correctly-typed List<Integer>.

How to pass a linked list in Java?

I am having trouble understanding how to pass a linkdlist into a method that display that list as a stack. I am aware i havent specifed the type of list but my instructor said that it would not matter for this purpose. but I am still learning so I'm not to sure if I am passing the linkedlist correctly into the method.
import java.util.LinkedList ;
import java.util.ListIterator;
public class UseStacksAndQueues{
public static void main(String[] args) {
StacksAndQueues sQ = new StacksAndQueues();
String [] days = {"mon","tue","wed","thur","fri", "sat","sun"};
LinkedList aList = new LinkedList();
LinkedList newList = new LinkedList();
//load array of string objects into linked list
aList = sQ.methodOne(days);
//display linked list as a stack
sQ.methodTwo(aLits);
the method.
//display a linked list as a stack
public LinkedList methodTwo(aList){
for(int i = aList.size; i <= 0; i--)
{
System.out.println(aList.get(i));
}
}//end method two
Your call to the method is correct. The method itself is the problem. You need to specify the type of object being passed into your method.
public LinkedList<String> methodTwo(LinkedList<String> aList){
...
}
You also need to specify the type of your LinkedList in angled brackets, as shown above. That includes when you create your list before passing it around.
LinkedList<String> aList = new LinkedList<>();
The second pair of angled brackets can be empty, as shown above. This is a shortcut introduced in Java 7.
that would be correct. in java, objects are passed by reference (except for primitive types) so you will be able to perform all of the operations on the list you pass to methodTwo.
Please refer to this post for an explanation
Is Java "pass-by-reference" or "pass-by-value"?
Having said that, you do not have any types associated with your List objects, so you will need to specify that.
so something like
public void methodTwo(LinkedList<String> aList){
for(int i = aList.size; i <= 0; i--)
{
System.out.println(aList.get(i));
}
}//end
i have the return type as void, as that is all thats needed if you only need methodTwo for display purpose
and you will also need to declare as
LinkedList<String> aList = new ArrayList<String>();

Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

The map function simply iterates through the integer array and applies function to it and then adds it to an output array. I'm getting this error and I can't seem to find where it's casting an Object to an Integer. The map function returns an Integer array and is sent to printArray which takes an Integer array. Any ideas?
public static void main(String[] args)
{
Function<Integer,Integer> function = new CalculateSuccessor<Integer,Integer>();
Integer[] integerArray={1,3,4,2,5};
printArray(map(function, integerArray));
}
I've removed the rest of the code because the solution was found to be the <Integer, Integer> after Function.
its because you use generics Function<Integer,Integer> guava is trying to cast the values you pass as to Integer but you actualy pass Object.
I assume that your printArray method expects an Object[]
An Object[] is not an definition of a "super" instance of Integer[] even if Object is a super class of Integer.
Assume this code was valid:
Object[] array = new Integer[10];
then this would also be valid
array[0] = new Car("Mercedes");
But the latter should not be possible. Hence the "inheritance" restriction on arrays.
Same goes for list for example
List<Object> myList = new ArrayList<Integer>();
It will give you a compiler error.

array of pair, ArrayList in java

how can I make array of ArrayList or Pair Class which I made myself at the code below.
ex1)
import java.util.*;
class Pair{
static int first;
static int second;
}
public class Main{
public static void main(String[] args){
Vector<Pair>[] v = new Vector<Pair>[100](); //this gives me an error
}
}
1.why the code above gives me an error?
2.my goal is to make an array of vector so that each index of vector holds one or more Pair classes. How can I make it?
another example) : array of ArrayList
import java.util.*;
public class Main{
public static void main(String[] args){
ArrayList<Integer> arr = ArrayList<Integer>(); //I know this line doesn't give error
ArrayList<Integer>[] arr = ArrayList<integer>[500]; // this gives me an error
}
}
3.why does the code above give me an error?
4.my goal is to make an array of ArrayList so that each index of Array has ArrayList/Queue/Vector/Deque whatever. How can I make it?
How about a full generic solution:
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
The syntax you have used is not what Java uses. If you want to have an array of ArrayLists then do:
ArrayList[] arr = new ArrayList[100];
for(int i=0; i<arr.length; i++)
{
arr[i] = new ArrayList<Pair>(); // add ArrayLists to array
}
Here the type argument <Pair> specifies that the ArrayList should contain items of type Pair. But you can specify any type you wish to use. The same goes for ArrayList, you could replace ArrayList with Vector in the example.
It would be best to use an ArrayList instead of an array in the example. Its much easier to maintain without worrying about the changing length and indexes.
Hope this helps.
public static void main(String[] args){
Vector[] v = new Vector[5];
for(int i=0;i<5;++i){
v[i]= new Vector<Pair>();
}
}
I don't know java that well, but don't you want to do:
ArrayList<ArrayList<Pair>> v = new ArrayList<ArrayList<Pair>>();
Try to break down what containers you need in your question. Your goal is to make a ArrayList (ok, the outer ArrayList satisfies that purpose) that has one or more pair classes in that. "That has" means that "each item in the ArrayList is this type". What would we use to store one or more Pair classes? Another Vector/List of tyoe Pair. So each item in the outer ArrayList is another ArrayList of Pairs.
Note: I moved everything to ArrayList because I read that Vector is somewhat deprecated and they serve similar functions. You may want to check on this.
This example should help with with the next part of your question, but let me know if it doesn't,

Categories