Iterating one the lists, when it is not known which one should be on the outer loop - collections

I have 2 lists that are built at runtime:
List<ReportEntity> existingEntities = //get somehow
List<Device> devices = //get somehow
ReportEntity.java
...
private String deviceId;
...
Device.java
...
private String id;
...
The lists have objects of different types!
The sizes of these lists will not be known until runtime. The requirement is to process the common elements in the list differently than the remaining. Since the sizes are not known before-hand, I can't put any one list in the outer for-loop.
Please can some light be shed around how to handle this?
Example loop structure when existingEntities.size() > devices.size():
for (ReportEntity exitingEntity : existingEntities) {
for (Device device : devices) {
if (existingEntity.getDeviceId().equals(device.getId())) {
// do something;
}
}
}
// HOW DO WE NO KNOW WHAT DEVICES WERE NOT PROCESSED

Related

TraversalEngine abstract class utilisation

Firstly, i am sorry but i don't speak english very well. Secondly, i have a problem with nodes which are put in a gridpane. In fact, if the focus is taken by the first one wich is located on the top left side, when i push the tab key, the focus is not taken by the other which is located on the right.
People ask me to use the traversalEngine abstract class in order to solve this problem. Nevertheless, when i try to implement an engine object, it doesn't work if i put the parameters which are shown everywhere on the web:
TraversalEngine engine = new TraversalEngine(gridPane, false) {
It ask me to remove the parameters. If i do it, i don't have access to the trav method. In fact, it is the getRoot method which appears and can be implemented :
TraversalEngine engine = new TraversalEngine() {
#Override
protected Parent getRoot() {
// TODO Auto-generated method stub
return null;
}
}
Is there something which can be make in order to solve this problem ?
Thanks you for your help
Vinz
The traversal order for focusing nodes in a parent is the order in which they occur in the child list. Assuming every child contains at most one focusable node you could simply add the children line by line or reorder the children.
This could be done programmatically of course, but adding the children in the correct order in the first place would be more efficient...
public static int getColumnIndex(Node n) {
Integer i = GridPane.getColumnIndex(n);
return i == null ? 0 : i;
}
public static int getRowIndex(Node n) {
Integer i = GridPane.getRowIndex(n);
return i == null ? 0 : i;
}
grid.getChildren().sort(Comparator.comparingInt(ContainingClass::getRowIndex).thenComparingInt(ContainingClass::getColumnIndex));

How to bind lists like an updating ForEach?

Here is a sample code:
public class Example3 {
class Point {
int x, y; // these can be properties if it matters
}
class PointRepresentation {
Point point; // this can be a property if it matters
public PointRepresentation(Point point) {
this.point = point;
}
}
Example3() {
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = FXCollections.observableArrayList();
points.forEach(point -> representations.add(new PointRepresentation(point)));
}
}
I have a data holder Point and a data representor PointRepresentation. I have a list of points and i would like that for each point in the list there would be an equivalent representation object in the second list. The code I gave works for the initialization but if there is any change later the above will not update.
What I am doing now is using a change listener to synchronize the lists (add and remove elements based on the change object) and it's OK but i am wondering if there's a simpler solution. I was looking for something like a "for each bind" that means: for each element in one list there is one in the other with the specified relation between them [in my case its that constructor]. In pseudocode:
representations.bindForEach(points, point -> new PointRepresentation(point));
Things I looked at: extractors for the list but that sends updates when a property in the objects they hold change and not when the list itself changes. So in my case if x in the point changes i can make an extractor that notifies it. Another thing I looked at is http://docs.oracle.com/javase/8/javafx/api/javafx/beans/binding/ListBinding.html, so maybe a custom binding does it but I don't know if it's simpler.
Also is there a similar solution for arrays instead of lists? i saw the http://docs.oracle.com/javase/8/javafx/api/javafx/collections/ObservableArray.html as a possibility.
The third-party library ReactFX has functionality for this. You can do
ObservableList<Point> points = FXCollections.observableArrayList();
ObservableList<PointRepresentation> representations = LiveList.map(points, PointRepresentation::new);
This will update representations automatically on add/remove etc changes to points.

what is the disadvantage of vector over arraylist in collection and why?

i am unable to understand what is the actual concept behind synchronization that is used in vector class please answer.
Because yesterday, i used a vector which is much better than array list. So here i am little bit confused.
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> vc=new Vector<String>();
// <E> Element type of Vector e.g. String, Integer, Object ...
// add vector elements
vc.add("Vector Object 1");
vc.add("Vector Object 2");
vc.add("Vector Object 3");
vc.add("Vector Object 4");
vc.add("Vector Object 5");
// add vector element at index
vc.add(3, "Element at fix position");
// vc.size() inform number of elements in Vector
System.out.println("Vector Size :"+vc.size());
// get elements of Vector
for(int i=0;i<vc.size();i++)
{
System.out.println("Vector Element "+i+" :"+vc.get(i));
}
}
}
Well, As you know Vector is a grandPa of ArrayList and is there since JDK 1.0.
If you read JavaDoc, Java itself recommends restricted use of Vector
As of the Java 2 platform v1.2, this class was retrofitted to
implement the List interface, making it a member of the Java
Collections Framework. Unlike the new collection implementations,
Vector is synchronized. If a thread-safe implementation is not needed,
it is recommended to use ArrayList in place of Vector.
Internal implementation ArrayList & Vector are same. Both are used array to data in back end.
All the public methods are synchronized. So Performance wise its slow. Its a very old implementation.
Apart that setSize method available in Vector.
As per JavaDoc
Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.

Iterating over Java Lists - how do I recognise the final element?

I have a List for example
{ "in" , "out", "rec", "auth" }
... but the content of the list is not predictable.
When iterating the list list how can we know we have reached last element?
I want to apply different logic for the last element.
Example : List list = new ArrayList be the list, you need not traverse to get the last( element, you can get it by list.get(list.size()-1) and perform the logic you wanted.
The "classic" way to iterate through a Java List is to use List.iterator() to obtain an Iterator, then use the Iterator's methods to step through the list values.
This works with anything that implements Iterable, not just Lists.
// assuming myList implements Iterable<Type>
Iterator<Type> iterator = myList.iterator();
while(iterator.hasNext()) {
doSomethingWith(iterator.next())
}
Since JDK 1.5, there has been a shortcut in the language to achieve the same thing:
// assuming myList implements Iterable<Type>
for(Type item : myList) {
doSomethingWith(item);
}
However, while convenient in many situations, this syntax doesn't give you full access to all the information Iterator has.
If you want to treat the last element of the list specially, one method might be:
Iterator<Type> iterator = myList.iterator();
while(iterator.hasNext()) {
Type item = iterator.next();
if(iterator.hasNext() {
doSomethingWith(item);
} else {
// last item
doSomethingElseWith(item);
}
}
Your specific situation - creating a comma-separated string representation of the list, without a trailing comma:
Iterator<String> iterator = myList.iterator();
StringBuilder buffer = new StringBuilder();
while(iterator.hasNext()) {
buf.append(iterator.next());
if(iterator.hasNext() {
buf.append(",")
}
}
All this assumes that there's a reason you want to avoid using list.size().
You should consider using LinkedList instad of ArrayList. It has getLast() method.

different hashtable cacheItem with similar data values or separate cacheItems for each data value – which is an efficient approach?

I have broadly two different classes of data caching requirements based on data size:
1) very small data (2-30 characters) – this includes such things as the type code for a given entityId. The system is based upon the concept of parent-child entity hierarchy and actions are authorized against values that are built in combination with entity type code. Caching these type codes for different entities saves time on db fetch.
2) medium/Large data – This is general data like products description and pages.
I'm confused as to which approach is better suited for first class of data.
I can cache it like this:
HttpRuntime.Cache.Insert("typeCode" + entityId, entityTypeCode);
or like this:
Dictionary<int, string> etCodes =
(Dictionary<int, string>)HttpRuntime.Cache["typeCode"];
etCodes[entityId] = entityTypeCode;
Clearly, In the second approach, I'm saving on unnecessary cache items for each entityId.
or, having Cache object populated with several items of such small size is okay.
Which of these approachs is good in terms of performance and overhead?
Personally I would take your second approach of one single object and use a custom object instead of a Dictionary.
This would enable me to later control more aspects like expiration of items within the object or changing the implementation.
I would do it similar to this:
public class MyCacheObject
{
public static MyCacheObject
{
get
{
// ...Omitted locking here for simplification...
var o = HttpRuntime.Cache["MyCacheObject] as MyCacheObject;
if ( o = null )
{
o = new MyCacheObject();
HttpRuntime.Cache["MyCacheObject] = o;
}
return o;
}
}
public object GetEntity( string id, string code )
{
// ...
}
public void SetEntity( object entity, string id, string code )
{
// ...
}
// ...
}
If you have a custome base class for the entities, the GetEntity and SetEntity methods could be optimized further.

Resources