convert object to string getting can not cast error - java

I have a list of object List in which at 4th index it has list of integer [1,2,3,4,5]
Now I want to get list into a comma separated string.
below is my try, but it giving error as can not cast.
for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
String groupedItemIds = (String)objArr[4];
}
how to do this?

Try the following:- use toString()
String output = relationshipInfo.toString();
output = output.replace("[", "");
output = output.replace("]", "");
System.out.println(output);
[UPDATE]
If you want fourth Object only then try:
Object[] objArr = relationshipInfo.toArray();
String groupedItemIds = String.valueOf(objArr[4]);

You cannot type cast Object to String unless the Object is indeed a String. Instead you can do the following -
Call toString() on it. Override it in your class.

you want "comma separated string" . So, you iterate over the 4th index and read each integer and do "" + int1 +" , " + int2 etc.. you can do this (in) by overriding your toString() method..

You could try:
String groupedItemIds = Arrays.asList( objArr[4] ).toString();
This will produce: groupedItemIds = "[1,2,3,4,5]"

Try this :
for(Object[] objArr : relationshipInfo)
{
if(null != objArr[4])
{
String groupedItemIds = String.valueOf(objArr[4]);
}
}
Ref :
public static String valueOf(Object obj)
Returns the string representation of the Object argument.
Link.
Difference between use of toString() and String.valueOf()
if you invoke toString() with a null object or null value, you'll get a NullPointerExcepection whereas using String.valueOf() you don't have to check for null value.

It looks like you are using arrays not Lists in which case you can use:
String groupedItemIds = java.util.Arrays.toString(objArr[4]);

You cannot cast an Object to an uncomatible type
for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
List<Integer> groupedItemIds = (List<Integer)objArr[4];;
//Loop over the integer list
}

Integer Array or Integer can not be cast to a String.
try
for(Object[] objArr : relationshipInfo){
if(null != objArr[4]){
String groupedItemIds = new String (objArr[4]); // or String.valueOf(objArr[4]);
}
Update
If the 4th index is a Array then try
String groupedItemIds = Arrays.asList(objArr[4]).toString();
which will give you a comma delimitered String

I resolved my problem by belwo code
byte[] groupedItemIdsArr = (byte[])objArr[4];
String groupedItemIds = new String(groupedItemIdsArr);

Related

How to convert values to string? [duplicate]

I want the Java code for converting an array of strings into an string.
Java 8+
Use String.join():
String str = String.join(",", arr);
Note that arr can also be any Iterable (such as a list), not just an array.
If you have a Stream, you can use the joining collector:
Stream.of("a", "b", "c")
.collect(Collectors.joining(","))
Legacy (Java 7 and earlier)
StringBuilder builder = new StringBuilder();
for(String s : arr) {
builder.append(s);
}
String str = builder.toString();
Alternatively, if you just want a "debug-style" dump of an array:
String str = Arrays.toString(arr);
Note that if you're really legacy (Java 1.4 and earlier) you'll need to replace StringBuilder there with StringBuffer.
Android
Use TextUtils.join():
String str = TextUtils.join(",", arr);
General notes
You can modify all the above examples depending on what characters, if any, you want in between strings.
DON'T use a string and just append to it with += in a loop like some of the answers show here. This sends the GC through the roof because you're creating and throwing away as many string objects as you have items in your array. For small arrays you might not really notice the difference, but for large ones it can be orders of magnitude slower.
Use Apache commons StringUtils.join(). It takes an array, as a parameter (and also has overloads for Iterable and Iterator parameters) and calls toString() on each element (if it is not null) to get each elements string representation. Each elements string representation is then joined into one string with a separator in between if one is specified:
String joinedString = StringUtils.join(new Object[]{"a", "b", 1}, "-");
System.out.println(joinedString);
Produces:
a-b-1
I like using Google's Guava Joiner for this, e.g.:
Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");
would produce the same String as:
new String("Harry, Ron, Hermione");
ETA: Java 8 has similar support now:
String.join(", ", "Harry", "Ron", "Hermione");
Can't see support for skipping null values, but that's easily worked around.
From Java 8, the simplest way I think is:
String[] array = { "cat", "mouse" };
String delimiter = "";
String result = String.join(delimiter, array);
This way you can choose an arbitrary delimiter.
You could do this, given an array a of primitive type:
StringBuffer result = new StringBuffer();
for (int i = 0; i < a.length; i++) {
result.append( a[i] );
//result.append( optional separator );
}
String mynewstring = result.toString();
Try the Arrays.deepToString method.
Returns a string representation of the "deep contents" of the specified
array. If the array contains other arrays as elements, the string
representation contains their contents and so on. This method is
designed for converting multidimensional arrays to strings
Try the Arrays.toString overloaded methods.
Or else, try this below generic implementation:
public static void main(String... args) throws Exception {
String[] array = {"ABC", "XYZ", "PQR"};
System.out.println(new Test().join(array, ", "));
}
public <T> String join(T[] array, String cement) {
StringBuilder builder = new StringBuilder();
if(array == null || array.length == 0) {
return null;
}
for (T t : array) {
builder.append(t).append(cement);
}
builder.delete(builder.length() - cement.length(), builder.length());
return builder.toString();
}
public class ArrayToString
{
public static void main(String[] args)
{
String[] strArray = new String[]{"Java", "PHP", ".NET", "PERL", "C", "COBOL"};
String newString = Arrays.toString(strArray);
newString = newString.substring(1, newString.length()-1);
System.out.println("New New String: " + newString);
}
}
You want code which produce string from arrayList,
Iterate through all elements in list and add it to your String result
you can do this in 2 ways: using String as result or StringBuffer/StringBuilder.
Example:
String result = "";
for (String s : list) {
result += s;
}
...but this isn't good practice because of performance reason. Better is using StringBuffer (threads safe) or StringBuilder which are more appropriate to adding Strings
String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';
String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s
result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s
result = String.join("", strings);
//Java 8 .join: 3ms
Public String join(String delimiter, String[] s)
{
int ls = s.length;
switch (ls)
{
case 0: return "";
case 1: return s[0];
case 2: return s[0].concat(delimiter).concat(s[1]);
default:
int l1 = ls / 2;
String[] s1 = Arrays.copyOfRange(s, 0, l1);
String[] s2 = Arrays.copyOfRange(s, l1, ls);
return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
}
}
result = join("", strings);
// Divide&Conquer join: 7ms
If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.
String array[]={"one","two"};
String s="";
for(int i=0;i<array.length;i++)
{
s=s+array[i];
}
System.out.print(s);
Use Apache Commons' StringUtils library's join method.
String[] stringArray = {"a","b","c"};
StringUtils.join(stringArray, ",");
When we use stream we do have more flexibility, like
map --> convert any array object to toString
filter --> remove when it is empty
join --> Adding joining character
//Deduplicate the comma character in the input string
String[] splits = input.split("\\s*,\\s*");
return Arrays.stream(splits).filter(StringUtils::isNotBlank).collect(Collectors.joining(", "));
If you know how much elements the array has, a simple way is doing this:
String appendedString = "" + array[0] + "" + array[1] + "" + array[2] + "" + array[3];

converting object to string error

can somebody please tell me if this is the right way to convert an object to string? Firstly the error below
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String word = it.next(); // Object to string error
String input = responseMap.get(word);
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
Then i did this, and it worked.
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String input = responseMap.get(it.next());// i put it here
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
I was so curious about the error. I made a little research, since i'm just learning i don't know if this is right or wrong. it worked, but is it right?
public String generateResponse(HashSet<String> words){
Iterator it = words.iterator();
while(it.hasNext()){
String word = it.next().toString();// added toString()
String input = responseMap.get(word);
if(input != null){
return input;
}
}
return pickDefaultResponse();
}
Iterator it = words.iterator();
This statement ignores the type parameter of the iterator. That means the return type of it.next() is Object, which can't be assigned to String without a cast.
responseMap.get(it.next());
works, because the parameter of Map.get has the type Object.
String word = it.next().toString();
Will work too, since the Object returned by it.next() actually is a String and therefore toString returns the same String.
This would work too:
String word = (String) (it.next());
But I recommend adding a type parameter to the Iterator variable:
Iterator<String> it = words.iterator();
while(it.hasNext()){
String word = it.next();
// ...
Note: "Ignoring" a type parameter is a bad idea most times.
String word = it.next()
firstly it does not have a " ; " to end the string, and secondly you need to explicitly cast it to String
change the code to String word = (String)it.next();
change raw type iterator to generic type.
Iterator it = words.iterator();
to
Iterator<String> it = words.iterator();
Yup it is
You cant assign a hashset directly to a string.
You have to convert it. using the toString method
As much to my info, in ur second case...
when you use the below code
"String input = responseMap.get(it.next());"
There are many overloaded methods for different datatypes. So when u provided a hashset directly. It worked correctly

Check null value of map

I am getting map as result and when I am getting value I need to convert it to String like below:
a.setA(map.get("A").toString());
but if it returns null than it throws nullPointerException, so I change it with below:
a.setA(map.get("A")!=null?map.get("A").toString():"");
but there are more than 20 fields for that I am doing the same so I just want to do like below:
String val = "";
a.setA(val=map.get("A")!=null?val.toString():"");
but it returns blank all time, I have just simple question is can't I use variable like this? or is there any other option for doing the same?
Use a method. And avoid calling get() twice:
private String valueToStringOrEmpty(Map<String, ?> map, String key) {
Object value = map.get(key);
return value == null ? "" : value.toString();
}
...
String a = valueToStringOrEmpty(map, "A");
String b = valueToStringOrEmpty(map, "B");
Now repeat after me: "I shall not duplicate code".
Why don't you create a util method to this like:
public String getMapValue(Map m, String a){
String s = m.get(a);
if(s == null)
return "";
else
return s;
}
Now you just need to call this method:
String val = getMapValue(map,"A");
a.setA(val);
with Java 8 you can do the following:
a.setA(map.getOrDefault("A", "").toString());
Problem is that val wont get the value you want until map.get("A")!=null?val.toString():"" is evaluated, try this instead:
String val = "";
a.setA((val=map.get("A"))!=null?val.toString():"");
so you get sure that val=map.get("A") evaluates before the whole thing.
You can try this
Map<String,String> map=new HashMap<>();
Set<String> keySet=map.keySet();
Iterator it=keySet.iterator();
while (it.hasNext()){
if(map.get(it)!=null){
a.setA(map.get(it).toString());
}else{
a.setA(null);
}
}

java kdb - casting C to string

I am trying to cast kx.c class flip object to a string:
String test = (String) c.at(flip[0],1)
However I am getting an error stating that I cannot cast C objects to String. Does anyone know what I can cast a kx C object to return a string?
Not too sure what you mean exactly by "C objects" but I assume that it is a char array - the Java type to represent a Kdb string. Here is what you can do:
Object[] data = this.flip.y;
Object[] columnData = (Object[]) data[row];
char[] data = (char[]) columnData[i];
return String.valueOf(data);
If you are trying to retrieve a kdb symbol then it will be a String array.
Object[] data = this.flip.y;
Object[] columnData = (Object[]) data[row];
String data = (String) columnData[i];
return data;
A c.Flip is a mapping from keys to values. In particular, it has String keys and Object values, stored in two arrays inside the Flip (called x and y respectively).
If you want to get the value for the key "foo", then you can do something like this:
c.Flip myFlip = ...; // Get hold of your flip
Object value = myFlip.at("foo"); // Throws ArrayIndexOutOfBoundsException if "foo" is not found
If you happen to know that the value will be a String, then you can cast it:
String strValue = (String) value; // Throws ClassCastException if value isn't a String
You can also combine the last two lines into one, like so:
String strValue = (String) myFlip.at("foo");

Problem when copying array of different types using Arrays.copyOf

I am trying to create a method that pretty much takes anything as a parameter, and returns a concatenated string representation of the value with some delimiter.
public static String getConcatenated(char delim, Object ...names) {
String[] stringArray = Arrays.copyOf(names, names.length, String[].class); //Exception here
return getConcatenated(delim, stringArray);
}
And the actual method
public static String getConcatenated(char delim, String ... names) {
if(names == null || names.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i = 0; i < names.length; i++) {
String n = names[i];
if(n != null) {
sb.append(n.trim());
sb.append(delim);
}
}
//Remove the last delim
return sb.substring(0, sb.length()-1).toString();
}
And I have the following JUnit test:
final String two = RedpillLinproUtils.getConcatenated(' ', "Shervin", "Asgari");
Assert.assertEquals("Result", "Shervin Asgari", two); //OK
final String three = RedpillLinproUtils.getConcatenated(';', "Shervin", "Asgari");
Assert.assertEquals("Result", "Shervin;Asgari", three); //OK
final String four = RedpillLinproUtils.getConcatenated(';', "Shervin", null, "Asgari", null);
Assert.assertEquals("Result", "Shervin;Asgari", four); //OK
final String five = RedpillLinproUtils.getConcatenated('/', 1, 2, null, 3, 4);
Assert.assertEquals("Result", "1/2/3/4", five); //FAIL
However, the test fails on the last part with the exception:
java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:2763)
Can someone spot the error?
Since you can't store, say Integers, in a String[] array, there is no way you can just copy an array of objects into an array of Strings. You have to somehow go through .toString() on each object.
This solution would for instance work:
public static String concat(char delim, Object... objs) {
if (objs == null || objs.length == 0) return "";
StringBuilder sb = new StringBuilder();
for (Object o : objs)
sb.append(delim).append(o);
return sb.substring(1);
}
As a side note on varargs; I doubt you need to check if objs == null. The compiler will turn a call of the from concat(",", "a", "b", "c") into concat(",", new Object[] {"a", "b", "c"), thus I can't see how objs could ever equal null. -->
The cause
You can't put an Integer in a String[]. That's why you get ArrayStoreException. Arrays.copyOf does no conversion.
From the API:
T[] copyOf(U[] original, int newLength, Class< ? extends T[]> newType)
Throws: ArrayStoreException - if an element copied from original is not of a runtime type that can be stored in an array of class newType
The ArrayStoreException API has an example:
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
See also
JLS 10.10 Array Store Exception
The fix
That said, you actually don't need a String... and Arrays.copyOf to a String[]. Your getConcatenated can just take Object... and it'd work just fine.
public static String getConcatenated(char delim, Object... objs) {
if(objs == null || objs.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for (Object o : objs) {
if(o != null) {
if (sb.length() > 0) sb.append(delim);
sb.append(o.toString().trim());
}
}
return sb.toString();
}
Now you can do the following:
System.out.println(getConcatenated(';', "Shervin", null, "Asgari", null));
// prints "Shervin;Asgari"
System.out.println(getConcatenated('/', 1, 2, null, 3, 4));
// prints "1/2/3/4"
System.out.println(getConcatenated(':', " ", null, "boo", "boo"));
// prints "boo:boo"
Note that this follows the intended specification in the original code, i.e. trim() and skips null.
You can only copy Strings into a String[].
System#arraycopy and Arrays#copyOf do not do any type conversions, you have to turn the objects into Strings one by one yourself, for example by calling String#valueOf (the null-safe version of Object#toString).
Why not change the method to accept Object... instead of String... and call String.valueOf(obj) on each of them.

Categories