This question already has answers here:
How do I assert an Iterable contains elements with a certain property?
(9 answers)
Closed 6 years ago.
I have a Java Object that contains another java object that is a set. For Example:
Public States {
private Set<City> cities = new HashSet(0);
// Setters and Getters Here
}
Public City {
private String dummyValue;
// Setters and Getters Here
}
I would like to test this object to ensure it contains values that I have modified in a method. For example I was trying:
Set<City> citySet = citySetInfoFromAnotherMethod;
assert citySet.iterator().next().equals("Dallas");
However I know this will not work because a Set does not have an order such as a list does.
So in conclusion, in what way can I test this object to see if values another method assigns to it appear after I do something to it.
You can use the excellent Hamcrest matchers library to achieve what you want (it ships built in with earlier versions of JUnit, but not with later ones).
You'll want to do something like:
Set<City> citySet = citySetInfoFromAnotherMethod;
assertThat(citySet, contains("Dallas"));
Of course that won't work because your set items are a City object, not a String, but you can use more Hamcrest matchers to achieve that too!
Set<City> citySet = citySetInfoFromAnotherMethod;
assertThat(citySet, contains(hasProperty("Name", eq("Dallas"))));
Alternatively (and IMHO better) approach would be to use a property matcher from Hamcrest to extract the City name.
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I'm making a small program that simulates some of a bank's basic functions. I created a class Branch and used an ArrayList to hold Branch objects that the user would like to add. If I would like to specifically display all of the Branch names (one of the fields in the class) of each object contained in ArrayList<Branch>, would that be possible? Or is it better to create an array of strings that will hold each branch name? Currently, when I try to print out the ArrayList it outputs the pointer (I think) to the console.
I can put my code up upon request.
You basically answered it yourself. You just iterate over the ArrayList, and do stuff for each object.
For example, in a for-each-loop:
List<Branch> branchList = new ArrayList<Branch>();
for (Branch branch : branchList ) {
// iterates through all your objects contained in the list
// use the object here
}
Of course there are many more ways to do this, as it was already pointed out in a comment.
You need to iterate over your array to get the objects data.
Here is some example with Java 8 streams:
List<Branch> branches = new ArrayList<Branch>();
// prints out the name of the object
branches.stream().map(branchName -> branch.getName()).forEach(System.out::println);
I found a nice blogpost which explains streams and how you can work with it. In my opinion the best way to work with Lists:
https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
This question already has answers here:
Is there a better way to combine two string sets in java?
(11 answers)
Union two ImmutableEnumSets with Guava
(1 answer)
Combine multiple Collections into a single logical Collection?
(5 answers)
Closed 2 years ago.
I'm using Guava's Immutable collections. Basically I have two helper functions that return ImmutableSets both of which contain data that are instances of inner classes that implement a common interface. However, I want to merge the two Immutable sets in order into a single ImmutableSet, in the actual function.
private static ImmutableSet<Fruit.seedless> helper1(args...) {...}
private static ImmutableSet<Fruit.seeded> helper2(args...) {...}
public ImmutableSet<Fruit> MainFunction() {...}
This is an example of how you can combine 2 or more ImmutableSet objects and create another ImmutableSet. This uses the Integer type for the parameterized type because I do not have access to your Fruit class.
Set<Integer> first = ImmutableSet.of(1);
Set<Integer> second = ImmutableSet.of(2);
Set<Integer> third = ImmutableSet.<Integer>builder()
.addAll(first)
.addAll(second)
.build();
ArrayList<ParkingList> Parkings = new ArrayList<ParkingList>();
ArrayList<ParkingList> ParkingsDB = new ArrayList<ParkingList>();
for example, Parkings may contain (a,b,c,d) objects and ParkingsDB may contain (a,b)
how can i find c,d
i tried using this method but it didint work,
ArrayList<ParkingList> temp = new ArrayList<ParkingList>(Parkings);
temp.removeAll(ParkingsDB);
my class definition:
public class ParkingList {
Rectangle R;
String Name;
int level;
String BuildingName;
public ParkingList(String BuildingName,String Name, Rectangle R, int level) {
this.R=R;
this.Name=Name;
this.level=level;
this.BuildingName=BuildingName;
}
}
i just wanna know, was my method that i used above a correct method? maybe i have another problem i need to fix.
my criteria is , two objects are equal only if all of the attributes in one object are the same in another object.
in order to utilise removeAll on a collection of custom types you'll need to provide an implementation of the equals method and if possible also the hashCode method as it is used by certain collections in the collection API.
another solution would be to utilise removeIf and specify the criteria which defines when two or more objects are equal.
e.g.
ArrayList<ParkingList> temp = new ArrayList(Parkings);
temp.removeIf(x -> ParkingsDB.stream()
.anyMatch(e -> e.getName().equals(x.getName())));
in this case, the criteria is when any given object in temp has the same name as any given object in ParkingsDB then it shall be removed from the temp list.
now you'll simply need to decide whether to provide your own implementation of equals and hashCode or utilise the example above; in all cases, you'll need to provide a criteria which defines when two given objects are equal.
This is irrelevant to the problem at hand, but you don't seem to respect the Java naming conventions at all.
variables as well as methods (except constructors which is a special type of a method) should start with a lowercase letter and follow the camelCase naming convention i.e rather than Parkings it should be parkings, rather than Name it should be name etc.
Also, you seem to have freely exposed the state of ParkingList. you should enforce encapsulation here by making all the variables private and only provide getters and setters where necessary.
The easiest way for you, as it was already mentioned - to implement ParkingList.equals() method. For example you can generate it by IDE.
Than your code:
temp.removeAll(ParkingsDB);
will work as you expected. This happens since list implementation basically depends on equals() method for checking elements.
You may also use streams:
ArrayList<ParkingList> temp = Parkings.stream()
.filter(parking -> !ParkingsDB.contains(parking))
.collect(Collectors.toList());
This question already has answers here:
how to deserialize a json/gson that could be a string , object ,or list
(3 answers)
Closed 8 years ago.
When using gson to a class, one of the classes variables can either be a String or a List. Is it possible to catch and fix this without making a whole new class where one class has String and the other List?
Here is an example of the class:
public class JsonClass
{
private List<Integer> range;
public List<Integer> getRange() { return range; }
}
This only works when the range is a List with Integers, but it can also just be a String. The gson message is: "Expected STRING but was BEGIN_ARRAY".
I don't think that u can do that. String and List are totally different things. As Java is strongly typed, u should create a new class to be able to deal it with 2 ways
You have two problems.
First, how will your code use this JsonClass if it doesn't know the type of range. You can declare it as Object, but you'll have to check the instance type and cast it every time. Alternatively, you can have two variables, one for each type. But then, what do you do with the other? Do you leave it null? Do you put a default value, empty list, empty string? These are things you should consider first.
Second, Gson, by default, looks at the declared type of a field in order to deserialize JSON. If you declare it as Object, it will use some known defaults. What you can do is create and register a TypeAdapter which will contain logic for deserializing both a JSON array and a JSON string depending on what it finds.
I don't recommend either of the approaches above. I suggest you try to fix the JSON you are receiving to send a single type or map it to different types based on some external information, ie. not based on the JSON itself.
This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 7 years ago.
Is There a java util method, or a short way to sort an Array of some type by an attribute of that type. I currently have an array of Choice type objects where each have a getText() method that returns the visual representation of the choice. I can make a long method that creates an array of the choices texts, sort them, get their ordered index and then order the choices by that index, but I surely think there is some kind of a shortcut.
Any Suggestions?
Collections.sort(list, new Comparator<Choice>(){
public int compare (Choise c1, Choice c2) {
return c1.getText().compareTo(c2.getText());
}
});
add check for null if necessary
you can move comparator to external class and use reflection to read custom field from any object. but this will make code less understandable