List received like object in a function - java

This feature may receive in the variable object 2 types of list types: List<String> or List<Integer>. I have this function:
private void isAList(Object example)
{
}
I can iterate of two ways:
isAList(new ArrayList<String>);
or
isAlist(new ArrayList<Integer>);
I want to know if the first element of this List is a String or an Integer. How I can know which is the first element of this Object (always received a list). this is my code:
private void isAList(Object example)
{
if (example != null && example instanceof List<?> && **FIRST_ELEMENT_OF_example??** instanceof String)
{
for (String cad : (List<String>)example)
{
XXXXXX MY CODE XXXXXX
}
}
}

Solution:
private void isAList(Object example)
{
if (example != null && !((List<?>)example).isEmpty() && ((List<?>)example).get(0) instanceof String)
{
for (String cad : (List<String>)example)
{
// YOUR CODE
}
}
}

Already an accepted answer, but more can be done:
First:
private <T> void isAList(List<T> example)
{
if (example.isEmpty()) {
return;
}
if (example.get(0) instanceof Integer) { // Not null (!!) and Integer
// ...
} else {
// null or String
List<String> list = Collections.checkedList(example, String.class);
// ...
}
}
And the use of Collections.checkedList.
List<String> list = Collections.checkedList(list, String.class);

I would do something like this:
private void isAList(Object example){
if (example == null)
//handle it, return....
try {
List<String> list = (List<String>) example;
for (String cad : list){
XXXXXX MY CODE XXXXXX
}
}
catch (ClassCastException e){
//handle exception
}
}
There is no need to do so many checks, by using a try-catch block you ensure that if everything goes as planned you will iterate through your list of strings.
If it doesn't, there are two possibilities: the object is not a list, or the objects inside the list are not strings, in both cases a ClassCastException should be thrown and by catching it you should be good.

Related

Cannot resolve method startsWith by using anyMatch

Can some one tell me please what is wrong here. My code is fine until I added this portion of code if (!tmp.isEmpty()) { return e.isEmpty(); }
The error is: Cannot resolve method startsWith(java.lang.String)
#Test
public void TestData() {
ArrayList<String> rootOpts = new ArrayList<String>();
rootOpts.add("aa");
rootOpts.add("bb");
rootOpts.add("ac");
ArrayList<String> allSiblings = new ArrayList<String>();
allSiblings.add("aa");
allSiblings.add("ac");
allSiblings.add("abc");
System.out.println("allMatch " + rootOpts.stream()
.map((e) -> {
System.out.println("e = " + e);
List<String> tmp = new ArrayList<String>();
tmp.addAll(allSiblings);
String[] CHs = {"ab","aa","ac"};
for (String chh : CHs) {
tmp.remove(chh);
}
if (!tmp.isEmpty()) {
return e.isEmpty();
}
return e;
})
.anyMatch(v -> v.startsWith("a")));
}
I am trying to rewrite the following code below(this code is contained in a method that is supposed to return a boolean value true or false):
for (Option e : rootOpts) {
List<String> tmp = new ArrayList<String>();
tmp.addAll(allSiblings);
if (e.getData() != null && !e.getData().getString().isEmpty()) {
String[] chs = {"ab","aa","ac"};
for (String ch : chs) {
tmp.remove(ch);
}
} else {
return false;
}
if (!tmp.isEmpty()) {
return false;
}
}
return true;
Thank you for your help guys
e.isEmpty() returns a boolean. In the following method anyMatch you want to invoke the method startsWith on this boolean but this method does not exist on boolean. So change your code to:
if (!tmp.isEmpty()) {
return ""; //or whatever string makes sense
}
e is of type String while e.isEmpty() is of type Boolean.
Therefore the return type of your function is Object.
Finally, Object does not have a startsWith function, contrary to the original String type that was returned which is why the compiler is complaining.
Look at the return type of isEmpty() - it's boolean. How are you planning to do startsWith on a boolean true/false? :) Stream predicts that it's possible to get boolean, and thus it cannot let you do startsWith on it.
if (!tmp.isEmpty()) {
return e.isEmpty();
}

How to search a list that contains specific dynamic values

I have a list of type Model_BarcodeDetail which conatins attributes like barcode, area,location,color etc.
when I enter any barcode in the edittext, I want to search that barcode in the list(list can have n number of similar barcodes with similar area and location or different area and location), if the barcode I entered and the similar barcode that is presnt in my list have same area and location then I want to doSomething() else doSomethingElse().
The code I tried is:
private List<String> barcodeList = new ArrayList<String>();
barcode = editText_barcode.getText().toString().trim();
if ((scanned_barcode != null
&& scanned_barcode.equalsIgnoreCase(barcode))) {
if ((!barcodeList.contains(barcode)) ) {
// if barcode I entered does not contains in the list
// It is working fine
barcodeList.add(barcode);//barcodeList contains only barcode
}
else if (barcodeList.contains(barcode) ) {
data = list.get(barcodeList.indexOf(barcode));
// here is the problem
// here I want to get data of the barcode that have similar area and
location
if (data.getArea() == selected_area
&& data.getLocation() == selected_loc) {
doSomething();
} else {
doSomethingElse();
}
}
Search your string in array list and get Object and then check location of barcode, here is sample code:
barcode = editText_barcode.getText().toString().trim();
if ((scanned_barcode != null
&& scanned_barcode.equalsIgnoreCase(barcode))) {
Model_BarcodeDetail model_barcodeDetail=getBarcodeDetails(barcode);
// for handling array do this in loop
if (model_barcodeDetail!=null && model_barcodeDetail.getArea() == selected_area && model_barcodeDetail.getLocation() == selected_loc) {
doSomething();
}else{
doSomethingElse();
}
}
/* your list can contain n number of similar bar code then change return type of this function to Model_BarcodeDetail[] */
private Model_BarcodeDetail getBarcodeDetails(Sttring barcode){
for (Model_BarcodeDetail model_barcodeDetail : list) {
if (barcode.eqauals(model_barcodeDetail.getBarcode)){
return model_barcodeDetail;
}
}
return null;
}
When your list looks something like:
List<Model_BarcodeDetail> list = new ArrayList<Model_BarcodeDetail>()
you can use an foreach loop:
barcode = editText_barcode.getText().toString().trim();
if ((scanned_barcode != null
&& scanned_barcode.equalsIgnoreCase(barcode))) {
if ((!barcodeList.contains(barcode))) {
// if barcode I entered does not contains in the list
// It is working fine
}
for (Model_BarcodeDetail model_barcodeDetail : list) {
if (model_barcodeDetail.getArea() == selected_area && model_barcodeDetail.getLocation() == selected_loc) {
doSomething();
break;
}
}
// Nothing found
doSomethingElse();
}

Can we get the exact location where the condition fails, in an If case having multiple conditions?

I am new to Java,
Here is my code,
if( a.name == b.name
&& a.displayname == b.displayname
&& a.linkname == b.linkname
......... )
return true;
else
return false;
I will call this method and have to check that all properties of objects 'a' and 'b'.
Each object will have more than 20 properties. So, it is will be tidy if i use if case for each property.
An exception is throwed if the return is false and I have to report which property fails.
Is there any easy method to find where the condition fails within the if case.
Pls help. Ask if you are not clear about the question.
The question is, would you like to continue checking if one of the conditions fails?
You could do something like comparator where you have interface:
public interface IComparator {
boolean compare(YourObject o1, YourObject o2);
String getComparatorName();
}
Next you create set of implementations of that interface:
NameComparator implements IComparator {
private name="Name Comparator";
#Override
public boolean compare(YourObject o1, YourObjecto2) {
return o1.getName().equals(o2.getName());
}
#Override
public String getComparatorName() {
return name;
}
}
Next you store set of these comparators in arrayList and you iterate through them and record which one fails by adding them to some other collection.. Hope that helps!
For instance you create array:
IComparator[] comparators = new IComparator[]{ new NameComparator, new DisplayNameComparator};
List<IComparator> failedComparationOperations = new ArrayList<IComparator>();
for(IComparator currentComparator : comparators) {
if(!currentComparator.compare(o1, o2)) {
failedComparationOperations.add(currentComparator);
}
}
for(IComparator currentComparator: failedComparationOperations)
{
System.out.println("Failed Comparation at: "+currentComparator.getComparatorName());
}
You may use reflection: browse what fields are defined, and check each of them using method equals. Print error message if they're not equal, give summary at the end.
boolean equals = true;
Field[] fields = a.getClass().getDeclaredFields();
for (Field f: fields){
f.setAccessible(true);
try {
if (!f.get(a).equals(f.get(b))){
System.out.println(f.getName() + ": " + f.get(a) + "!="+ f.get(b));
equals = false;
};
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("equals?: " + equals);
If you need to know which of the conditions has failed you should check each of the conditions independently.
It might be a little overkill if you are dealing with this single requirement, but what about the Strategy Design Pattern?
http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism
It should be an interesting option if you have other business rules that you can combine with this check.
If a and b are instances of the same class, let's assume A, and the fields are visible, then you can use reflections:
for (Field f : A.class.getFields()) {
try {
if (!f.get(a).equals(f.get(b))) {
throw new RuntimeException("Field " + f.getName() + " is different.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Without reflection you can't get maximum conciseness, but the followincg can help you to some extent. Make this kind of class:
class NamedEquals {
final String name;
final Object left, right;
NamedCondition(String name, Object left, Object right) { ...assign them... }
boolean areEqual() { return left.equals(right); }
}
Then make a List<NamedEquals>:
List<NamedEquals> conds = Arrays.asList(
new NamedEquals("name", left.name, right.name),
new NamedEquals("displayname", left. displayname, right.displayname),
...
);
And you can find if some of them fail:
for (NamedEquals eq : conds)
if (!eq.areEqual()) throw new ValidationException(eq.name);
Using a factory method can shorten the construction code:
static NamedEquals eq(String name, Object left, Object right) {
return new NamedEquals(name, left, right);
}
With that you can have
List<NamedEquals> conds = Arrays.asList(
eq("name", left.name, right.name),
eq("displayname", left. displayname, right.displayname),
...
);
How about?
// Adapted from your example:
if(!equalTo(a.name, b.name))
fail("name");
if(!equalTo(a.displayname, b.displayname))
fail("displayname");
... etc ...
...
// Allow for null values.
public boolean equalTo(Object a, Object b) {
return a != null ? a.equals(b) : b == null;
}
public void fail(String which) throws SomeException {
throw new SomeException("Failed on '"+which+"'!");
}
Another possible might be to turn each object into a Map<String,?>, perhaps by adding a Map<String,?> toMap() method to the value object, and implementing this by constructing a new map and dumping the value's fields into it. Then you can get the maps and do equals() on them.

How to produce error for item not being in array list

I'm trying to select an item from an array list by calling its ID number and I need a Dialog error to show up if the ID number is not associated with any item in the array list.
I know how to code a dialog box but I don't know how to make it pop out when the ID number I type in doesn't match anything in the array list.
for (Object myElement : myList) {
if (myElement.getId() == id) {
// handle gracefully
break;
}
}
// Make dialog box appear
As has been suggested, you probably want to use a HashMap for performance
To answer you question, I think you are looking for something like
int id = getMahId();
ArrayList<?> mahList = getMahList();
if (!mahList.contains(getMahId())
throw new IllegalArgumentException("Does not contain id");
However, I think you are looking for a map, possibly a HashMap. This more easily allows you to map an id to an item.
Boolean foundObject = false;
for (MyObject myObject : myList) {
if (id.equals(myObject.getId()) {
foundObject = true;
break;
}
}
if (!foundObject) {
//Show dialog here
}
Simple way:
List<MyClass> list = new ArrayList<MyClass>();
// add objects to list
String id; // get this from wherever
boolean found = false;
for (MyClass o : list) {
found |= o.getId().equals(id);
}
Better way is to override the equals() method to compare ids.
public class MyClass {
String id;
public boolean equals(Object o) {
return o instanceof MyClass &&
((MyClass)o).getId().equals(id);
}
// hash code should agree with equals
public int hashCode() {
return id.hashCode();
}
// rest of class omitted
}
Then to check, simply:
boolean found = list.contains(id);

Java: avoid checking for null in nested classes (Deep Null checking)

Imagine I have a class Family. It contains a List of Person. Each (class) Person contains a (class) Address. Each (class) Address contains a (class) PostalCode. Any "intermediate" class can be null.
So, is there a simple way to get to PostalCode without having to check for null in every step? i.e., is there a way to avoid the following daisy chaining code? I know there's not "native" Java solution, but was hoping if anyone knows of a library or something. (checked Commons & Guava and didn't see anything)
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
No, can't change the structure. It's from a service I don't have control over.
No, I can't use Groovy and it's handy "Elvis" operator.
No, I'd prefer not to wait for Java 8 :D
I can't believe I'm the first dev ever to get sick 'n tired of writing code like this, but I haven't been able to find a solution.
You can use for:
product.getLatestVersion().getProductData().getTradeItem().getInformationProviderOfTradeItem().getGln();
optional equivalent:
Optional.ofNullable(product).map(
Product::getLatestVersion
).map(
ProductVersion::getProductData
).map(
ProductData::getTradeItem
).map(
TradeItemType::getInformationProviderOfTradeItem
).map(
PartyInRoleType::getGln
).orElse(null);
Your code behaves the same as
if(family != null &&
family.getPeople() != null &&
family.people.get(0) != null &&
family.people.get(0).getAddress() != null &&
family.people.get(0).getAddress().getPostalCode() != null) {
//My Code
}
Thanks to short circuiting evaluation, this is also safe, since the second condition will not be evaluated if the first is false, the 3rd won't be evaluated if the 2nd is false,.... and you will not get NPE because if it.
If, in case, you are using java8 then you may use;
resolve(() -> people.get(0).getAddress().getPostalCode());
.ifPresent(System.out::println);
:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
REF: avoid null checks
The closest you can get is to take advantage of the short-cut rules in conditionals:
if(family != null && family.getPeople() != null && family.people.get(0) != null && family.people.get(0).getAddress() != null && family.people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
By the way, catching an exception instead of testing the condition in advance is a horrible idea.
I personally prefer something similar to:
nullSafeLogic(() -> family.people.get(0).getAddress().getPostalCode(), x -> doSomethingWithX(x))
public static <T, U> void nullSafeLogic(Supplier<T> supplier, Function<T,U> function) {
try {
function.apply(supplier.get());
} catch (NullPointerException n) {
return null;
}
}
or something like
nullSafeGetter(() -> family.people.get(0).getAddress().getPostalCode())
public static <T> T nullSafeGetter(Supplier<T> supplier) {
try {
return supplier.get();
} catch (NullPointerException n) {
return null;
}
}
Best part is the static methods are reusable with any function :)
You can get rid of all those null checks by utilizing the Java 8 Optional type.
The stream method - map() accepts a lambda expression of type Function and automatically wraps each function result into an Optional. That enables us to pipe multiple map operations in a row. Null checks are automatically handled under the neath.
Optional.of(new Outer())
.map(Outer::getNested)
.map(Nested::getInner)
.map(Inner::getFoo)
.ifPresent(System.out::println);
We also have another option to achieve the same behavior is by utilizing a supplier function to resolve the nested path:
public static <T> Optional<T> resolve(Supplier<T> resolver) {
try {
T result = resolver.get();
return Optional.ofNullable(result);
}
catch (NullPointerException e) {
return Optional.empty();
}
}
How to invoke new method? Look below:
Outer obj = new Outer();
obj.setNested(new Nested());
obj.getNested().setInner(new Inner());
resolve(() -> obj.getNested().getInner().getFoo())
.ifPresent(System.out::println);
Instead of using null, you could use some version of the "null object" design pattern. For example:
public class Family {
private final PersonList people;
public Family(PersonList people) {
this.people = people;
}
public PersonList getPeople() {
if (people == null) {
return PersonList.NULL;
}
return people;
}
public boolean isNull() {
return false;
}
public static Family NULL = new Family(PersonList.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
import java.util.ArrayList;
public class PersonList extends ArrayList<Person> {
#Override
public Person get(int index) {
Person person = null;
try {
person = super.get(index);
} catch (ArrayIndexOutOfBoundsException e) {
return Person.NULL;
}
if (person == null) {
return Person.NULL;
} else {
return person;
}
}
//... more List methods go here ...
public boolean isNull() {
return false;
}
public static PersonList NULL = new PersonList() {
#Override
public boolean isNull() {
return true;
}
};
}
public class Person {
private Address address;
public Person(Address address) {
this.address = address;
}
public Address getAddress() {
if (address == null) {
return Address.NULL;
}
return address;
}
public boolean isNull() {
return false;
}
public static Person NULL = new Person(Address.NULL) {
#Override
public boolean isNull() {
return true;
}
};
}
etc etc etc
Then your if statement can become:
if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...}
It's suboptimal since:
You're stuck making NULL objects for every class,
It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and
There are potentially some funny issues with subclassing and which NULL to use.
But if you really hate your == nulls, this is a way out.
Although this post is almost five years old, I might have another solution to the age old question of how to handle NullPointerExceptions.
In a nutshell:
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
}
Since there is a lot of legacy code still in use, using Java 8 and Optional isn't always an option.
Whenever there are deeply nested classes involved (JAXB, SOAP, JSON, you name it...) and Law of Demeter isn't applied, you basically have to check everything and see if there are possible NPEs lurking around.
My proposed solution strives for readibility and shouldn't be used if there aren't at least 3 or more nested classes involved (when I say nested, I don't mean Nested classes in the formal context). Since code is read more than it is written, a quick glance to the left part of the code will make its meaning more clear than using deeply nested if-else statements.
If you need the else part, you can use this pattern:
boolean prematureEnd = true;
end: {
List<People> people = family.getPeople(); if(people == null || people.isEmpty()) break end;
People person = people.get(0); if(person == null) break end;
Address address = person.getAddress(); if(address == null) break end;
PostalCode postalCode = address.getPostalCode(); if(postalCode == null) break end;
System.out.println("Do stuff");
prematureEnd = false;
}
if(prematureEnd) {
System.out.println("The else part");
}
Certain IDEs will break this formatting, unless you instruct them not to (see this question).
Your conditionals must be inverted - you tell the code when it should break, not when it should continue.
One more thing - your code is still prone to breakage. You must use if(family.getPeople() != null && !family.getPeople().isEmpty()) as the first line in your code, otherwise an empty list will throw a NPE.
If you can use groovy for mapping it will clean up the syntax and codes looks cleaner. As Groovy co-exist with java you can leverage groovy for doing the mapping.
if(family != null) {
if(family.getPeople() != null) {
if(family.people.get(0) != null) {
if(people.get(0).getAddress() != null) {
if(people.get(0).getAddress().getPostalCode() != null) {
//FINALLY MADE IT TO DO SOMETHING!!!
}
}
}
}
}
instead you can do this
if(family?.people?[0]?.address?.postalCode) {
//do something
}
or if you need to map it to other object
somobject.zip = family?.people?[0]?.address?.postalCode
Not such a cool idea, but how about catching the exception:
try
{
PostalCode pc = people.get(0).getAddress().getPostalCode();
}
catch(NullPointerException ex)
{
System.out.println("Gotcha");
}
If it is rare you could ignore the null checks and rely on NullPointerException. "Rare" due to possible performance problem (depends, usually will fill in stack trace which can be expensive).
Other than that 1) a specific helper method that checks for null to clean up that code or 2) Make generic approach using reflection and a string like:
checkNonNull(family, "people[0].address.postalcode")
Implementation left as an exercise.
I was just looking for the same thing (my context: a bunch of automatically created JAXB classes, and somehow I have these long daisy-chains of .getFoo().getBar().... Invariably, once in a while one of the calls in the middle return null, causing NPE.
Something I started fiddling with a while back is based on reflection. I'm sure we can make this prettier and more efficient (caching the reflection, for one thing, and also defining "magic" methods such as ._all to automatically iterate on all the elements of a collection, if some method in the middle returns a collection). Not pretty, but perhaps somebody could tell us if there is already something better out there:
/**
* Using {#link java.lang.reflect.Method}, apply the given methods (in daisy-chain fashion)
* to the array of Objects x.
*
* <p>For example, imagine that you'd like to express:
*
* <pre><code>
* Fubar[] out = new Fubar[x.length];
* for (int i=0; {#code i<x.length}; i++) {
* out[i] = x[i].getFoo().getBar().getFubar();
* }
* </code></pre>
*
* Unfortunately, the correct code that checks for nulls at every level of the
* daisy-chain becomes a bit convoluted.
*
* <p>So instead, this method does it all (checks included) in one call:
* <pre><code>
* Fubar[] out = apply(new Fubar[0], x, "getFoo", "getBar", "getFubar");
* </code></pre>
*
* <p>The cost, of course, is that it uses Reflection, which is slower than
* direct calls to the methods.
* #param type the type of the expected result
* #param x the array of Objects
* #param methods the methods to apply
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T[] apply(T[] type, Object[] x, String...methods) {
int n = x.length;
try {
for (String methodName : methods) {
Object[] out = new Object[n];
for (int i=0; i<n; i++) {
Object o = x[i];
if (o != null) {
Method method = o.getClass().getMethod(methodName);
Object sub = method.invoke(o);
out[i] = sub;
}
}
x = out;
}
T[] result = (T[])Array.newInstance(type.getClass().getComponentType(), n);
for (int i=0; i<n; i++) {
result[i] = (T)x[i];
}
return result;
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
and my favorite, the simple try/catch, to avoid nested null checks...
try {
if(order.getFulfillmentGroups().get(0).getAddress().getPostalCode() != null) {
// your code
}
} catch(NullPointerException|IndexOutOfBoundsException e) {}

Categories

Resources