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
Related
I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do
that in Java?
For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".
I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.
I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems
to be working. I was just wondering whether there is any simple way to achieve this.
That's simple with Java 8:
String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
For Java 7 replace the last line with:
boolean allMatch = true;
for (String string : strings) {
if (!string.equals(str)) {
allMatch = false;
break;
}
}
If you want to know if the array contains the string use ArrayList::contains()
String s = "HI";
ArrayList<String> strings = // here you have your string
if (string.contains(s)) {
// do your stuff
}
If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.
boolean areSame = true;
for (String str : strings) {
if (!str.equals(s)) areSame = false;
}
if (areSame) {
// all elements are same
}
1) You can the pass the arraylist into a set.
2) Now you can get the size of set, if it is equal to 1 that means all elements are same.
3) Now you can use the contains on set to check if your value is present in it or not.
public static void main(String[] args){
String toBeCompared="foo";
List<String> list=new ArrayList<String>();
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
Set<String> set=new HashSet<String>(list);
if(1==set.size()){
System.out.println(set.contains(toBeCompared));
}
else{
System.out.println("List has different values");
}
}
You can use this method to do that
private boolean allAreSame(ArrayList<String> stringList, String compareTo){
for(String s:stringList){
if(!s.equals(compareTo))
return false;
}
return true;
}
I would do it like this:
ArrayList<String> foos = new ArrayList<>();
String str = "foo";
for (String string : foos) {
if(string.equals(str)){
System.out.println("True");
}
}
I have a TreeSet filled with Strings that I want to use to see if any of the keys inside it start with a string outside the set, and be able to get that specific key and do something with it (put it in a string) For example my String is test 1 2 3 and I have a key in the set that is test 1 2 which should return true and tell me the key. The reason I am using a TreeSet is because I need a case-insensitive way to read the keys in my yaml file. I have used an iterator on the set before using
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext())
if (myString.startsWith(itr.next())){ }
but I could not the key that made the if statement true.
You're really close... it's this line that is wrong
if (myString.startsWith(itr.next())){ }
it should be this - because the key should start with the myString.
String theKey = null;
while(itr.hasNext()) {
theKey = itr.next();
if (theKey.startsWith(myString)) {
return theKey;
}
}
return null;
Call subSet() is more proper way for tree set than iterating over it.
myTreeSet.subSet(str, str + "\uffff")
I am not sure to get what you want:
Iterator<String> itr = myTreeSet.iterator();
while(itr.hasNext()) {
String myString = itr.next()
if (myString.startsWith(myString)){
System.out.println(myString);
}
}
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 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);
}
}
I am parsing content using the following code with jsoup.
try{
Elements divElements = jsDoc.getElementsByTag("div");
for(Element divElement : divElements){
if(divElement.attr("class").equals("article-content")){
textList.add(divElement.text());
text = textList.toString();
}
}
}
catch(Exception e){
System.out.println("Couldnt get content");
}
The only problem is the content is returned with brackets around it [] like that.
Im guessing it is becaue of the list i am setting it to. How can i remove these?
Replace:
text = textList.toString();
with:
text = textList.toString().replace("[", "").replace("]", "");
Using regex to replace the leading and trailing brackets, String.replace() doesn't work for the edge cases that the list's content contains brackets.
String text = textList.toString().replaceAll("(^\\[|\\]$)", "");
Yes, its because of the List. You have to Options:
Subclass whatever TextList is, and override toString()
or
String temp = textList.toString();
text = temp.subString(1, temp.size() -2);
For most objects, the toString() method is not intended to be used for display, but usually debugging. This is because the toString() method generally doesn't have a specific format and could vary depending on the particular class used. For example, a LinkedList and ArrayList could return different values from toString(). It's unlikely, but its something you should avoid relying on. Of course, if the object represents actual text (String, StringBuilder, CharSequence), the above doesn't apply.
Also, you are creating and assigning the string multiple times in the for loop. Instead, you should only create the string after the for loop is done.
To create the string you can roll your own or use a library like Apache commons lang, which has a StringUtils.join() utility method.
If you roll your own, it might look something like this:
Elements divElements = jsDoc.getElementsByTag("div");
Iterator<Element> iterator = divElements.iterator();
StringBuilder builder = new StringBuilder();
while (iterator.hasNext()){
Element divElement = iterator.next()
if (divElement.attr("class").equals("article-content")){
builder.append(divElement.text());
if (iterator.hasNext()) {
builder.append(", ");
}
}
}
text = builder.toString();
Implement your own method to create the String you need using iteration and StringBuffer. It is not a good practice to replace parentheses or substring such output.
You may override toString() method.
Set example:
class SetPrinter<E> extends HashSet<E> {
public SetPrinter(Set<E> set) {
super(set);
}
#Override
public String toString() {
Iterator<E> i = iterator();
if (!i.hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder();
for (; ; ) {
E e = i.next();
sb.append(e == this ? "(this Collection)" : e);
if (!i.hasNext())
return sb.toString();
sb.append(",");
}
}
}
Use:
new SetPrinter(SetToPrint).toString();
Simply use like this. It is working for me.
Text(text.toString().replaceAll('[', "").replaceAll(']', ''));