"Set of a Set" getter in a javabean - java

I have a javebean linked to a jsp page and have to manage a SET OF A SET.
The javabean structure is something like this:
public class QueryManagement {
...
private BigDecimal prob;
private Set<Set<Axiom>> explanations;
...
public void QueryExecute() {
...
QueryResult r = new QueryResult();
...
prob = r.getProbability();
explanations = r.getExplanations();
...
}
...
public BigDecimal getProb() {
return this.prob;
}
...
}
Now, from the jsp page I'm able to return prob with <%=QueryManagement.getProb()%> but I don't know how to return the vaule of a "Set of a Set". I tried a simple getter returning this.explanations, but it doesn't work. I know I have to return it recursively, but the doc I found at the documentation I found about Set can't help me. Can you explain me how to proceed and why?

public Set<Axiom> getExpl()
{ Iterator itr1 = explanations.iterator();
Set set ;
while(itr1.hasNext())
{
set = (HashSet)itr1.next();
// second iterator for internal set
}
return set ;
}

Related

Java Android, loop through all getters

I have a model like below:
public class Shifts{
private double h00;
private double h01;
private double h02;
private double h03;
public Shifts() {
}
public Shifts(double h00, double h01, double h02, double h03) {
this.h00 = h00;
this.h01 = h01;
this.h02 = h02;
this.h03 = h03;
}
public double getH00() {
return h00;
}
public void setH00(double h00) {
this.h00 = h00;
}
public double getH01() {
return h01;
}
public void setH01(double h01) {
this.h01 = h01;
}
public double getH02() {
return h02;
}
public void setH02(double h02) {
this.h02 = h02;
}
public double getH03() {
return h03;
}
public void setH03(double h03) {
this.h03 = h03;
}
}
I'm calling this model in a recycle adapter to update the UI and on the onBindViewHolder, I do like this:
holder.h00.setText(fooList.get(position).getH00()));
holder.h01.setText(fooList.get(position).getH01()));
holder.h02.setText(fooList.get(position).getH02()));
holder.h03.setText(fooList.get(position).getH03()));
In reality, this model has a lot of getters and setters and I was trying to loop through them so I can do something like this:
for (int i = 0; i < holder.shift_layout.getChildCount(); i++) {
//shift_layout is the Layout which holds all the views
View v = holder.shift_layout.getChildAt(i);
if (v instanceof TextView) {
v.setText(Hour(fooList.get(position).getGetter()));
}
}
Is there a way to use Java reflection or any method to loop through all getters of a model and then invoke them?
Looking over the SO I found some answers but with not any success to invoke the getters.
The other answers provided, especially Magnus, definitely get the job done. They are valid answers. The only difference between this solution and the others is that this will ensure that the method name starts with getH which seems to be pattern. It also checks if the return type is of type double to help ensure the correct method is being returned.
Shifts shifts = new Shifts(1, 2, 3, 4);
Method[] methods = shifts.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().startsWith("getH") && method.getReturnType() == double.class) {
double value = (double) method.invoke(shifts);
}
}
This code iterates over all methods of the class obj and if method name starts with 'get' it invokes the method m on instance obj and assigns the result to object:
final Object obj;
for (Method m : obj.getClass().getMethods())
if (m.getName().startsWith("get") && m.getParameterTypes().length == 0) {
final Object object = m.invoke(obj);
// do something
}
}
Yes, there is a way you can loop through getters by reflections. You should first make some kind of list with names of attributes.
I did it once with HashMap and setters, then I iterated through that hash map with:
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
var setterName = "set" + entry.getKey().toUpperCase();
Method setter = instanceOfMyClassWithSetters.getClass().getMethod(setterName, Integer.class);
setter.invoke(instanceOfMyClassWithSetters, entry.getValue());
}
That Integer.class is a setter parameter so I suppose you don't need that part.

Getter is used to add value in dynamoDB

I have an attribute called Attribute which is Set in dynamoDB(not mandatory), all the values for the attributes will be sent through an api which will be added into dynamoDB. I am using
#DynamoDBAttribute(attributename = Attribute)
private set<String> Attribute
public Set<String> getAttribute() {
if(CollectionUtils.isNullOrEmpty(Attribute)) {
return ImmutableSet.of(DEFAULT_ATTRIBUTE);
} else {
return ImmutableSet.copyOf(Attribute);
}
}
public void setAttribute(final Set<String> Attribute) {
if (CollectionUtils.isNullOrEmpty(Attribute)) {
this.categories = ImmutableSet.of();
} else {
this.categories = ImmutableSet.copyOf(Attribute);
}
}
I am expecting my dynamoDB table to have an empty set when we don't pass in an attribute value in the request we use, but instead of that, it is saving DEFAULT_ATTRIBUTE as the value of the field Attribute.
My DynamoDBMapperConfig.Savebehavior has default UPDATE, but I see that while saving a new value all the Savebehavior works the same.
If anyone knows the issue please help me with this, I have been trying to debug this from a long time. I want to know why the value in getAttribute is getting stored as the Attribute value?
Try this instead:
private set<String> Attribute
#DynamoDBTyped(DynamoDBMapperFieldModel.DynamoDBAttributeType.SS)
public Set<String> getAttribute() {
return Attribute;
}
public void setAttribute(final Set<String> Attribute) {
this.Attribute = Attribute;
}
DynamoDBMapper will handle the String Set for you. You just need to use the right annotation.
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html

Cleaner way to filter collections in Java 7/Guava?

I have the following classes:
class ServiceSnapshot {
List<ExchangeSnapshot> exchangeSnapshots = ...
...
}
class ExchangeSnapshot{
Map<String, String> properties = ...
...
}
SayI have a collection of ServiceSnapshots, like so:
Collection<ServiceSnapshot> serviceSnapshots = ...
I'd like to filter the collection so that the resulting collection of ServiceSnapshots only contains ServiceSnapshots that contain ExchangeSnapshots where a property on the ExchangeSnapshots matches a given String.
I have the following untested code, just wondering is there a cleaner/more readable way to do this, using Java 7, and maybe Google Guava if necessary?
Updtae: Note also that the code sample I've provided below isn't suitable for my purposes, since I'm using iterator.remove() to filter the collection. It turns out I cannot do this as it is modifying the underlying collection , meaning subsequent calls to my method below result in fewer and fewer snashots due to previous calls removing them from the collection - this is not what I want.
public Collection<ServiceSnapshot> getServiceSnapshotsForComponent(final String serviceId, final String componentInstanceId) {
final Collection<ServiceSnapshot> serviceSnapshots = getServiceSnapshots(serviceId);
final Iterator<ServiceSnapshot> serviceSnapshotIterator = serviceSnapshots.iterator();
while (serviceSnapshotIterator.hasNext()) {
final ServiceSnapshot serviceSnapshot = (ServiceSnapshot) serviceSnapshotIterator.next();
final Iterator<ExchangeSnapshot> exchangeSnapshotIterator = serviceSnapshot.getExchangeSnapshots().iterator();
while (exchangeSnapshotIterator.hasNext()) {
final ExchangeSnapshot exchangeSnapshot = (ExchangeSnapshot) exchangeSnapshotIterator.next();
final String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
if (foundComponentInstanceId == null || !foundComponentInstanceId.equals(componentInstanceId)) {
exchangeSnapshotIterator.remove();
}
}
if (serviceSnapshot.getExchangeSnapshots().isEmpty()) {
serviceSnapshotIterator.remove();
}
}
return serviceSnapshots;
}
Using Guava:
Iterables.removeIf(serviceSnapshots, new Predicate<ServiceSnapshot>() {
#Override
public boolean apply(ServiceSnapshot serviceSnapshot) {
return !Iterables.any(serviceSnapshot.getExchangeSnapshots(), new Predicate<ExchangeSnapshot>() {
#Override
public boolean apply(ExchangeSnapshot exchangeSnapshot) {
String foundComponentInstanceId = exchangeSnapshot.getProperties().get("ComponentInstanceId");
return foundComponentInstanceId != null && foundComponentInstanceId.equals(componentInstanceId);
}
});
}
});
I may have a ! missing or inverted somewhere, but the basic strategy is to remove any ServiceSnapshot objects that do not have any ExchangeSnapshot whose ID matches.

checking whether an object is present in a List of Objects on the basis of some member variable

suppose I have defined a List as
private BlockingQueue<MyDelayed> DelayedIds = new DelayQueue<>();
class MyDelayed is like:
private class MyDelayed implements Delayed {
private String myId;
private Long creationTime;
MyDelayed (String myId) {
this.myId= myId;
this.creationTime = System.currentTimeMillis();
}
String getMyId() {
return this.myId;
}
#Override
public long getDelay(TimeUnit unit) {
//TODO
}
#Override
public int compareTo(Delayed o) {
//TODO
}
}
Now suppose that I want to add an Object of class MyDelayed in DelayedIds list.
I can do it by using add function.
But If I want to add obbject in list only if list does not contain an object of class MyDelayed which has the same myId attribute which I am trying to insert.
Obviously DelayedIds .contains(new MyDelayed(myId)) will not work.
Is there any easy way to check this thing ?
Am I missing something ?
You could write something like this and compare every element in the list to see if it contains your id. If at any point you find a matching one you return true, if the loop finished having found none it returns false.
public boolean contains(String id){
for (MyDelayed md : DelayedIds){
if(md.getMyId().equals(id)){
return true;
}
}
return false;
}
Now to check before adding you would do something like:
if(!contains(myNewObject.getMyId())){
DelayedIds.add(myNewObject)
}
Also, I'd suggest that you rename DelayedIds to delayedIds in order to follow coding standards (see Variables).

Java ConcurrentModificationException when using list.remove()

I've got a method called removeSup which is supposed to remove an object Supplement from a list of supplements.
this is the code for the method:
private static void removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
Iterator<Supplement> iterator = listToRemoveFrom.iterator();
while(iterator.hasNext()){
if(iterator.next().equals(supToRemove)){
iterator.remove();
}
}
}
there is a class called magazine which defines the list of supplements.
public class Magazine {
private List<Supplement> supList;
public List<Supplement> getSupList() {
return this.supList;
}
public void setSupList(List<Supplement> supList) {
this.supList = supList;
}
public Magazine(Double cost, String _name){
this.supList = new ArrayList<>();
this.weekCost = cost;
this.name = _name;
}
}
the class supplement has the following constructor
public Supplement(String _name, Double _price, String _magName ){
this.name=_name;
this.price=_price;
this.magName = _magName;
}
in the main class client there is a search that the user can do to remove a certain Supplement
private static void searchSup(){
System.out.println("Search for Supplement");
String search = scanner.nextLine();
for (Supplement sup : magazine.getSupList()) {
if (!sup.getSupName().equalsIgnoreCase(search)) {
//do something
}
else{
removeSup(sup,magazine.getSupList());
}
}
}
the main method in the client class is as follows:
private Magazine magazine;
public static void main(String[] args) {
magazine = new Magazine(3.0, "pop");
List<Supplement> startList = new ArrayList<>();
startList.add(new Supplement("Nat Geo", 3.0,"pop"));
startList.add(new Supplement("Discovery", 5.0,"pop"));
startList.add(new Supplement("Health", 6.3,"pop"));
startList.add(new Supplement("IT", 8.3,"pop"));
magazine.setSupList(startList);
searchSup();
}
When I run this program and type any of the added supplements, i get an error
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Client.searchSup(Client.java:131)
at Client.searchSup(Client.java:140)
at Client.main(Client.java:588)
is it the for loop i am using to search giving me an error? if so how would i go about fixing this?
You generally shouldn't modify a Collection while iterating over it. It's fine to modify elements, but you really shouldn't remove something from a Collection while iterating. See here: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html. Also, the Javadoc for ConcurrentModificationException may be helpful.
You might try returning a new list with the Supplement removed:
private static List<Supplement> removeSup(Supplement supToRemove, List<Supplement> listToRemoveFrom) {
List<Supplement> filteredSupplements = new ArrayList<Supplement>();
for(Supplement supplement : listToRemoveFrom) {
if(!suppplement.equals(supToRemove)){
filteredSupplements.add(supplement);
}
}
return filteredSupplements;
}
It seams that the "magazine" is local var in the method of main, not accessible to searchSup.Fix it like
private void searchSup(Magazine magazine)
{
//...
}
and more details if you can provide, the codes in Line 131 and 140 will be helpful.
I figured out that the search i was doing was not working with what i wanted to do so i created a method which returns an integer of the Supplement in the list.
private static int indexOfSup(List<Supplement> supSearchList, String nameOfSup) {
for (Supplement sup : supSearchList) {
if (sup.getSupName().equalsIgnoreCase(nameOfSup)) {
return supSearchList.indexOf(sup);
}
}
return -1;
}
i then use this integer to remove from the list.
a simple List.Remove(index) worked fine
Thanks for all the replies.

Categories

Resources