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");
Related
How can I convert a String into a HashMap?
String value = "{first_name = naresh, last_name = kumar, gender = male}"
into
Map<Object, Object> = {
first_name = naresh,
last_name = kumar,
gender = male
}
Where the keys are first_name, last_name and gender and the values are naresh, kumar, male.
Note: Keys can be any thing like city = hyderabad.
I am looking for a generic approach.
This is one solution. If you want to make it more generic, you can use the StringUtils library.
String value = "{first_name = naresh,last_name = kumar,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
if you are using StringUtils which is contained in apache.commons.lang package.
You can do it in single line, for any object type not just Map.
(Since I use Gson quite liberally, I am sharing a Gson based approach)
Gson gson = new Gson();
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);
What it does is:
gson.toJson(value) will serialize your object into its equivalent Json representation.
gson.fromJson will convert the Json string to specified object. (in this example - Map)
There are 2 advantages with this approach:
The flexibility to pass an Object instead of String to toJson method.
You can use this single line to convert to any object even your own declared objects.
String value = "{first_name = naresh,last_name = kumar,gender = male}"
Let's start
Remove { and } from the String>>first_name = naresh,last_name = kumar,gender = male
Split the String from ,>> array of 3 element
Now you have an array with 3 element
Iterate the array and split each element by =
Create a Map<String,String> put each part separated by =. first part as Key and second part as Value
#Test
public void testToStringToMap() {
Map<String,String> expected = new HashMap<>();
expected.put("first_name", "naresh");
expected.put("last_name", "kumar");
expected.put("gender", "male");
String mapString = expected.toString();
Map<String, String> actual = Arrays.stream(mapString.replace("{", "").replace("}", "").split(","))
.map(arrayData-> arrayData.split("="))
.collect(Collectors.toMap(d-> ((String)d[0]).trim(), d-> (String)d[1]));
expected.entrySet().stream().forEach(e->assertTrue(actual.get(e.getKey()).equals(e.getValue())));
}
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples
input : "a=0,b={a=1},c={ew={qw=2}},0=a"
output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
Should Use this way to convert into map :
String student[] = students.split("\\{|}");
String id_name[] = student[1].split(",");
Map<String,String> studentIdName = new HashMap<>();
for (String std: id_name) {
String str[] = std.split("=");
studentIdName.put(str[0],str[1]);
}
You can use below library to convert any string to Map object.
<!-- https://mvnrepository.com/artifact/io.github.githubshah/gsonExtension -->
<dependency>
<groupId>io.github.githubshah</groupId>
<artifactId>gsonExtension</artifactId>
<version>4.1.0</version>
</dependency>
Using Java Stream:
Map<String, String> map = Arrays.stream(value.replaceAll("[{}]", " ").split(","))
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()));
Arrays.stream() to convert string array to stream.
replaceAll("[{}]", " "): regex version to replace both braces.
split(","): Split the string by , to get individual map entries.
s.split("=", 2): Split them by = to get the key and the value and ensure that the array is never larger than two elements.
The collect() method in Stream API collects all objects from a stream object and stored in the type of collection.
Collectors.toMap(s -> s[0].trim(), s -> s[1].trim()): Accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.
I am creating a class to sort some data.
class data{
public String text;
public String day;
public String direction;
}
dados vetor[]={};
Now I have to have to change a varible and I am doing it this way:
vetor[0].text="dumb text";
But I am gettting this error:
Attempt to write to field java.lang.String on a null object reference
Unless you reassigned the array to something else, this is your problem.
dados vetor[]={};
You create an empty array - there is no data object at vetor[0] for you to set the text of. If you know the number of elements you'll have when you declare the array, you can use the following to create an array to hold all of them.
dados[] vetor = new dados[10];
To actually create an element in that array and set its text, you need to create a new object.
vetor[0] = new data();
vetor[0].text = "Some text";
Alternatively, create and set the values for the data object before adding it to the array:
data myData = new data();
myData.text = "Some text";
vetor[0] = myData;
You probably did something like :
vetor[0] = someInstanceOfData.text; // Store value in array
However now vetor[0] contains the value of the text field (i.e. a String).
You can not access the text field later by doing vetor[0]. This refers to the String that is stored in that array. So if later the value of the text field changes, the vector will still contain the old.
Hence vetor[0].text="dumb text"; is not assigning the text field of some instance of the data class, but instead is trying to assign a new value to the String that results from vetor[0].
EDIT : If you want to change the value of the text field :
Data test = new Data(); // Make an instance of the Data class
test.text = "A String"; // Assign a value
If you want to make an array (of strings? or data objects?)
Data[] arr = {new Data(), new Data(), new Data()}; // Using the litteral
String[] arrOfStrings = {test.text, test.day, test.direction};
If you want to access/assign e.g. text from a data object storen in arr
arr[0].text = "Another String";
arrOfStrings[0].text = ...; // Not possible because it is storing strings not Data objects!
If you don't know the length before hand, you can not use an array (as they are of fixed length). Instead you could use List's which are of variable length.
List<Integer> test = new ArrayList<Integer>();
test.add(1); // Add elements
test.size(); // How long is my array at the moment?
test.get(0); // Access first element (index 0) --> 1
Applying this to your code :
dados testObject = new dados(); // create a "dados" object
List<dados> testList = new ArrayList<dados>();
testList.add(testObject);
testList.get(0); // Get object on index 0 (hence the first), hence "testObject"
To sort the ArrayList of dados objects you should implement a custom comparator to sort the objects like you want
public class OwnComparator implements Comparator<Dados> {
#Override
public int compare(Dados obj1, Dados obj2) {
return obj1.text.compareTo(obj2.text); // Sort based on "text" field
}
}
The actual sorting
Collections.sort(testList, new OwnComparator());
I am assuming your class name is "dados" and not "data".
Your array does not have any elements, hence the error.
Initialize your array to a certain number of elements and then assign the text property.
dados[] vetor = new dados[10];
vetor[0] = new dados();
vetor [0].text = "xx";
dados[] vetor2 = {new dados(), new dados()}; // initialize to 2 elements
vetor2[0].text = "xx";
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);
I have a method return type as ArrayList<String> which is also reading an argument of the same type. Now how do I type cast or modify my BigDecimal to read that value?
public static ArrayList<String> currencyUtilArray(ArrayList<String> amountStr ) {
BigDecimal amount = new BigDecimal(ArrayList<String> amountStr);
//How do I define that the amountStr is ArrayList<String> and need to place in BigDecimal amount one after another till the end of the List
return amountStr;
}
Or do I need to do
You can't type cast a String to a BigDecimal or vice versa.
If the strings in the array are meant to represent a number when concatenated then do something like this:
StringBuilder sb = new StringBuilder();
for (String s : amountStr) {
sb.append(s);
}
BigDecimal amount = new BigDecimal(sb.toString());
On the other hand, if each String represents a distinct number:
for (String s : amountStr) {
BigDecimal amount = new BigDecimal(s);
// ... and do something with it ...
}
I don't think you are referencing it correctly. You can't convert the whole ArrayList as an AL of type string to a Big Decimal.
First, change the ArrayList amountStr from within the new BigDecimal(--); and reference a single String from within the ArrayList.
Meaning you would have to loop through the whole thing, adding it into amount:
BigDecimal amount = new BigDecimal(amountStr.get(0));
For(int i = 1; i < amountStr.size(); i++){
amount = amount.add(new BigDecimal(amountStr.get(i)));
}
I believe that should give you what you need when it is returned.
what i understand is you want to convert the list elements into BigDecimal Array. If so you can do as below:
BigDecimal[] amount = new BigDecimal[amountStr.size()];
for (int i=0;i<amountStr.size();i++) {
amount[i] = new BigDecimal(amountStr.get(i));
}
I want to ask a Java String[] question. In the java, if a variable convents to another, it can add the (String), (int), (double),... before the variable in the left hand side. However, is there something like (String[]) in Java as I want to convent the variable into (String[]).
Yes, there is (String[]) which will cast into an array of String.
But to be able to cast into a String array, you must have an array of a super type of String or a super type of array (only Object, Serializable and Cloneable).
So only these casts will work :
String[] sArray = null;
Object[] oArray = null;
Serializable[] serArray = null;
Comparable[] compArray = null;
CharSequence[] charSeqArray = null;
Object object = null;
Serializable serializable = null;
Cloneable cloneable = null;
sArray = (String[]) oArray;
sArray = (String[]) serArray;
sArray = (String[]) compArray;
sArray = (String[]) charSeqArray;
sArray = (String[]) object;
sArray = (String[]) serializable;
sArray = (String[]) cloneable;
What you call 'convert' is actually called 'cast'.
Casting variable has no effect on object itself. In other words, (String) x is not equivalent of x.toString()
String[] is a perfectly normal Java class, just like any other. Try this, for example:
System.out.println(String[].class.getName());
You can also check 'Casting Objects' section in Java tutorial:
http://download.oracle.com/javase/tutorial/java/IandI/subclasses.html
What you want is probably not casting to String[], because your object is not a String[] but something else. What I think you are looking for would be something like this:
int someInt = 1;
long someLong = 2;
String[] strings = new String[] {
Integer.toString(someInt),
Long.toString(someLong)};
Yes, ofcourse.
Example:
String s1 = "test1";
String s2 = "test2";
Object obj [] = new Object[]{s1,s2};
String s[] = (String[]) obj;
System.out.println(s1);
System.out.println(s2);