0

Let's say I have this code where Element is a class:

import java.util.*; import java.io.*; public class HelloWorld { public static void main(String[] args) { Deque<Element> list = new LinkedList<Element>(); Element ele3 = new Element(); ele3.x = 3; ele3.y = 3; q.add(ele3); } } class Element { public int x; public int y; public String moves; } 

Let's say that during the run of my program, I come across an element with x=3 and y=3 which has better Element.moves than the previous one inside the queue. What I want is to remove the last one from the queue and add this one. To do this I could use the method removeFirstOccurrence of Dequeue. Since I don't know the last object's (with x=y=3) name how can I apply this method only knowing the object's x and y?

An other solution I thought is creating an array of objects and hash tuple (x,y) with i value so if I have (x,y) I could know that these belong in let's say A[i] object. In this case the problem is that I don't know how many objects I will need to create and thus can't initialize an array. Moreover if I use ArrayList or something similar I can't create let's say an A[i] object and refer to it using i.

Any ideas?

3
  • 3
    This is an XY problem. According to your requirements a deque could be the wrong answer to your problem. Please tell us what is your design problem first, not how to fix your code to solve a problem which could derive from a bad design choice. tl;dr: tell us your initial problem, not the problem which is deriving from your implementation. Commented Jul 30, 2019 at 13:48
  • You could stream() the collection, filter on the correct values of x and y, findFirst() then remove it if present. But the underlying problem is almost certainly that you're not using the correct data structure for the task at hand. Commented Jul 30, 2019 at 13:51
  • That sounds like you'd need a map where the key are the coordinates (or a set but doing lookups there would be harder). However, I agree with Jack: without knowing what you're actually trying to achieve it's hard to help. Of course we could suggest things like "iterate over the queue in reverse order (back to front) until you've found the object with matching coordinates and then remove that object" but there are probably much better approaches. Commented Jul 30, 2019 at 13:54

1 Answer 1

1

lambda expression to find the first Element with x=y=3

list.stream().filter( e -> (e.x == 3 && e.y == 3) ).findFirst().get(); 
Sign up to request clarification or add additional context in comments.

2 Comments

would this delete this element?
Nope. That only finds the item of interest. It can be removed with the appropriate command of the choosen Collection.