Check null value of map - java

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);
}
}

Related

Convert list to string using Java streams

I created a for each loop and I get list of price code but I want to
get same things without using any loop and perform this operation
using java8 for your reference I post my old code.
I want to change only this position of my code.
List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
List<String> priceCodeList = new ArrayList<String>();
for (ItemPriceCode ipc : itemPriceCodes) {
//get the string value from the list
priceCodeList.add(ipc.getPriceCode());
}
But I do not want to use any loop I want to get same result without
using any loop . To over come from this issue I try this way but I am
not get any success.
itemPriceCodes.stream().map(n -> String.valueOf(n)).collect(Collectors.toList());
Here This is my full code of this function
private Item getItemManufacturerPriceCodes(Item item) {
List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
List<String> priceCodeList = new ArrayList<String>();
for (ItemPriceCode ipc : itemPriceCodes) {
//get the string value from the list
priceCodeList.add(ipc.getPriceCode());
}
//pass this string value in query
List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);
//Convert list to map
Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect(
Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));// Object
for (ItemPriceCode ipcs : itemPriceCodes) {
ipcs.setManufacturerPriceCode(ipcToMFPNameMap.getClass().getName());
}
item.getItemPriceCodes()
.removeIf(ipcs -> DELETED.equals(ipcs.getRecordDeleted()));
return item;
}
It should be
List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).collect(Collectors.toList());
EDIT:
Java 16+
List<String> priceCodeList = itemPriceCodes.stream().map(ItemPriceCode::getPriceCode)).toList()
Although this would return an immutable list.
Furthur reading: Differences of Java 16's Stream.toList() and Stream.collect(Collectors.toList())?
Although it doesn't seem necessary considering the use case if you want to use String.valueOf() you need to override toString accordingly in your class, as String.valueOf() uses it to get the string representation.
Definition of valueOf()
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Thus to make your code work.. add this in your class
class ItemPriceCode{
.
.
.
public String toString(){
return this.getPriceCode();
}
}

as I find a string in another java

I wish you can help me I want to do is I have two variables of type string
String text = "HELLO HOW ARE YOU";
String value = "abc";
I want to do is see if any character of the variable values in text and contains tested but I only detects a single character but not
if(text.toUpperCase().contains(value.toUpperCase()))throw new Exception("NOT LETTERS");
You could use the List API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean hasAny = left.removeAll(right);
Basically this creates a List of each word then removes all the matches from the second in the first. A return value of true means the first List was modified, meaning it had matching values. You might even be able to compare the difference in size to determine how many matches there were.
You could also use Java 8's Stream API...
String text = "HELLO HOW ARE YOU";
String value = "abc";
List<String> left = new ArrayList<>(Arrays.asList(text.toUpperCase().split("")));
List<String> right = new ArrayList<>(Arrays.asList(value.toUpperCase().split("")));
boolean anyMatch = left.stream().anyMatch((String t) -> {
return right.contains(t);
});
Again, this will simply return true if the first List contains ANY of the values in the second List
Now, if you wanted to know which values actually matched, you might be able to use something like...
Set<String> collect = right.stream().filter((String t) -> {
return left.contains(t);
}).collect(Collectors.toSet());
System.out.println(collect);
Which in you example, would print
[A]
You can try like this:
public static boolean findLetters() {
String text = "HELLO HOW ARE YOU";
String value = "abc";
for (int i = 0; i < value.length(); i++) {
if (text.indexOf(value.toUpperCase().charAt(i)) == -1) {
return false;
}
}
return true;
}
Not sure if I understand the question quite well, but you may try this:
String text = "HELLO HOW ARE YOU";
String value = "abc";
for(char c : value.toUpperCase().toCharArray()) {
if (text.indexOf(c) != -1) {
throw new Exception("NOT LETTERS");
}
}

Java - Comparing a single String value with all the String values in an ArrayList

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");
}
}

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

convert object to string getting can not cast error

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);

Categories