Java List list to String [] - java

How would I convert
List list= new ArrayList();
to
String [] profArr= {};
I have tried doing
profArr = list.toArrary()
and
profArr = (String [])list.toArrary()
I get the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
I also have tried
String [] profArr= (String [])list.toArray(new String[0]);
and I get this error: The requested resource () is not available.
Here is how I create the list:
static List decode(int x)
{
List power2List = new ArrayList();
if (x < 0)
throw new IllegalArgumentException("Decode does not like negatives");
while (x > 0)
{
int p2 = Integer.highestOneBit(x);
x = x - p2;
power2List.add(p2);
}
return power2List;
}
List list= new ArrayList();
list= decode(rset.getInt("favprofs")); //rset being a result set which pulls one int

You need to be using list.toArray(new String[list.size()]). An Object[] is not type compatible with String[], despite every element in the Object[] being a String. Also, you should consider specifying the type parameter of your List to maintain type safety.

Basically you need to use
String profArr = list.toArray( < String array > (size))

you can use java collector
List<Tuple2<String, Boolean>> paras_check
String miss_params= paras_check.stream().map(e->e._1)
.reduce(",",(x,y)->(x+y));

Related

How to Sort a Nested List of strings

I want to sort the list by values in the list. I want to do multisorting based on few parameters in the list. Providing sample example how data looks like.
Note: I don't have feasibility to convert List<List<String>> into a list of objects.
List<List<String>> data = new ArrayList<>();
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
List<String> list3 = new ArrayList<>();
list1.add("Siva");
list1.add("20");
list1.add("Hyd");
list1.add("TA");
list1.add("India");
list2.add("Suresh");
list2.add("22");
list2.add("Banglore");
list2.add("KA");
list2.add("India");
list3.add("Ramesh");
list3.add("24");
list3.add("Chennai");
list3.add("TN");
list3.add("India");
data.add(list1);
data.add(list2);
data.add(list2);
I want to do multi sorting based on name, age and city.
It's just sample data. List of lists is dynamic. Sorting parameters will also change sometimes.
I want to do sorting on a list of lists of strings only.
Expected Output: List<List<String>> sortedData
Solution by Maintaining your Structure
If you can't really create a class wrapping the data in your nested List (for whatever reason), you could use the collection stream and define the sorted operation's logic as follows:
List<List<String>> listRes = data.stream()
.sorted((x, y) -> {
int res = x.get(0).compareTo(y.get(0)); //Comparing by name
if (res != 0) return res;
res = Integer.valueOf(x.get(1)).compareTo(Integer.valueOf(y.get(1))); //Comparing by age (numeric value)
if (res != 0) return res;
return x.get(2).compareTo(y.get(2)); //Comapring by city
})
.collect(Collectors.toList());
Link to test the code above:
https://ideone.com/RhW1VI
Alternative Solution
However, as it has been pointed out in the comments, a better approach would be to create a custom class representing your data in the nested List. Perhaps a simple record if you're using Java 14 or later with a factory method to retrieve an instance of your class from a nested List.
Then, with a stream you could map each nested list to your custom class and sort it with a Comparator.
Here is a snippet of the implementation:
public static void main(String[] args) {
List<List<String>> data = /* ... your initialization ... */
List<MyClass> listSorted = data.stream()
.map(list -> MyClass.createMyClass(list))
.sorted(Comparator.comparing(MyClass::getName).thenComparing(MyClass::getAge).thenComparing(MyClass::getCity))
.collect(Collectors.toList());
System.out.println(listSorted);
}
Mapping record
record MyClass(String name, int age, String city, String code, String country) {
public static MyClass createMyClass(List<String> list) {
if (list == null || list.size() < 5) {
return null;
}
MyClass mc = new MyClass();
mc.name = list.get(0);
mc.age = Integer.valueOf(list.get(1));
mc.city = list.get(2);
mc.code = list.get(3);
mc.country = list.get(4);
return mc;
}
}
Here there is also a link with both implementations:
https://ideone.com/UK9trV
In order to impose the order of lists inside a nested list need to define a Comparator.
As you've said that contents of the list will can't be predicted in advance, I assume that nested lists might be of arbitrary size and their sizes might not be equal.
A comparator that can handle such case might be written like that:
Comparator<List<String>> listComparator = new Comparator<>() {
#Override
public int compare(List<String> o1, List<String> o2) {
int limit = Math.min(o1.size(), o2.size());
for (int i = 0; i < limit; i++) {
int localResult = o1.get(i).compareTo(o2.get(i));
if (localResult != 0)
return localResult;
}
return o1.size() - o2.size();
}
};
In order to sort the list, you can apply method sort() on it (available with Java 8+) which expects a comparator:
data.sort(listComparator);
And you can make a defensive copy of the list before applying sort(), if its initial order might be useful for you:
List<List<String>> initialOrder = new ArrayList<>(data);
data.sort(listComparator);

Convert ArrayList to List<GenericModel> gives ClassCastException

I am converting stored procedure to complete JPA query. One of the SP query is as below which i am converting to entity class. I am converting this to a bean defined as Generic model which results in classcastexception.
SP query whose result set rs4 in java class is as follows:
rs4 Query: select command_value as descr from SCAN_COMMAND_NAME
where command_name = 'AAA' ORDER BY SEQ;
Here the result set rs4 is converted to GenericModel:
ResultSet rs4 = (ResultSet) cs.getObject(cnt++);
List commandRotateLi = new BeanProcessor().toBeanList(rs4,GenericModel.class);
session.setAttribute("coRotate", commandRotateLi);
///...
..///
ArrayList coRotate = (ArrayList) session.getAttribute("coRotate");
for(int x = 0; x < coRotate.size(); x++){
gm = (GenericModel) coRotate.get(x);
///
}
This above code works fine. Below is JPA converted code.
List<ScanCommandName> scanCommandList = new ArrayList<ScanCommandName>();
query = em.createNamedQuery("ScanCommandName.findByCommandName", ScanCommandName.class);
query.setParameter("commandName", Constants.IMAGE_MAGICK_ROTATE);
scanCommandList = query.getResultList();
scanCommandList.toString() gives me 5 ScanCommandName objects. I have to convert this List to List and loop through as above one but struck at class cast exception in the for loop.
ArrayList list = new ArrayList();
List<GenericModel> coRotate = null;
for(int y=0; y<scanCommandList.size(); y++){
ScanCommandName s = scanCommandList.get(y);
list.add(s.getCommandValue());
}
coRotate = (List<GenericModel>) (List) list;
I am now looping through the List coRotate but getting classcast at the 1st line in for loop.
for(int x = 0; x < coRotate.size(); x++){
gm = (GenericModel) coRotate.get(x);
///
}
java.lang.ClassCastException: java.lang.String cannot be cast to com.GenericModel
Any suggestions highly appreciated. thank you.
This is essentially what you are doing:
ArrayList list = new ArrayList();
List<SomeClass> slist;
list.add("String"); // <-- I'm guessing here based on exception
slist = (List<SomeClass>) list;
for (SomeClass s : slist) { // class cast exception
System.out.println(s);
}
class SomeClass {
}
Had you done this:
ArrayList<String> list = new ArrayList<>();
You could not have done this
slist = (List<SomeClass>) list;
And the error would have been caught at compile time.
Without knowing the details of your class structure, I suspect that to do what you want, coRotate needs to hold instances of GenericModel and
your ArrayList needs to be declared as ArrayList<GenericModel> = new ArrayList<>()

How can I solve java.lang.ArrayStoreException

Getting the following error in Android Studio:
Getting:
java.lang.ArrayStoreException: source[0] of type com.example.glide.ImageList cannot be stored in destination array of type java.lang.String[] in this line
Code:
ArrayList<ImageList> list = new ArrayList<>();
Object[] objNames = list.toArray();
String[] strNames = Arrays.copyOf(objNames, objNames.length, String[].class);
for(int j=0; j < strNames.length; j++){
strNames[j] = String.valueOf(list.get(j));
Log.d("String : {} ", strNames[i]);
}
Your program has lots of logical mistakes.
But try this one
public static void main(String[] args) {
ArrayList<ImageList> list = new ArrayList<>();
list.add(new ImageList()); //adding some dummy objects, you add yours
list.add(new ImageList());
String[] strNames = new String[list.size()];
for(int j=0; j < strNames.length; j++){
strNames[j] = String.valueOf(list.get(j));
Log.d("String : {} ", strNames[i]);
}
}
First, you have a list of ImageList items.
Second, this list is empty.
Third, you have defined an Array of String , and use Array.copyOf to populate it.
This won't work. You can cast ImageList to String directly.
What is that you are trying to achieve here?
Not sure, if you want a string representation of ImageList you can iterate over your "list" and call the .toString() method on each instance so you get the string representation of your instance.
Again not clear what you want?

How do I convert an object array into a map array?

I have the following code snippet:
//create map array and fill it with 3 dummy maps
Map[] mapArr= new Map[3];
for(int i = 0; i < mapArr.length; i++)
{
Map map = new HashMap();
mapArr[i] = map;
}
//now remove the second element (index == 1) from the map array
mapArr = ArrayUtils.removeElement(mapArr, 1);
My problem is witht he final line of code, because no matter what I try I get the error
Type mismatch: cannot convert from Object[] to Map[]
How do I convert the Object[] returned by removeElement() into a Map[]?
Did you try to cast it to "Map[]" ?
mapArr = (Map[]) ArrayUtils.removeElement(mapArr, 1);

Swings: storing the selected values from List into an array.

I made a List in java as under:
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList places = new JList(names) ;
Then in order to access the selected values I wrote in valueChanged method :
String[] emailID= places.getSelectedValuesList().toString[];
which is coming out to be incorrect ... Kindly help how should I rewrite this line so as the selected values get stored in array.
If you want to have all selected Items as an Array you can do something like this:
public static void main(String[] args){
String names[] = {"abc#gmail.com", "def#gmail.com","ghi#gmail.com","jkl#gmail.com"};
JList<String> places = new JList<String>(names) ;
places.setSelectedIndices(new int[]{0,1,2});
String[] emailIDs = places.getSelectedValuesList().toArray(new String[]{});
for(String s : emailIDs){
System.out.println(s);
}
}
Note:
I added <String> to the List, because I assume you always want to have Strings as values. That way you can get the List .toArray() method with a generic output. Else you'd need to get an Object[] (Object Array) and cast the values.
For Storing Selected Items in String Array you can try this
Object[] values = places.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Categories

Resources