Why Collection dont have and getAll method? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I may I not search enought but I haven't find any answer.
[[Collection]<T>][1] have an T get() methode, an void add(T t) method, and an void addAll(Collection<? extends T> c) method.
Then why we dont have an Collection<? extends T> getAll(Predicate<? extends T> p) method?
I know taht it souldn't be hard to make a subclass who implements it. But I dont understand why it is not already their.
Late edit:
Here a concrete exemple for sceptical.
I have to code :
wellsDisplayers = new ArrayList<DisplayWell>(Arrays.asList(displayerList.stream().filter(x->DisplayWell.class.isInstance(x)).toArray(DisplayWell[]::new)));
instead of :
wellsDisplayers = displayerList.getAll(x->DisplayWell.class.isInstance(x));
But you are right stream methode is really easy to use and understand, just like how java sould be.

I think you misunderstood the concept of a Collection. There is no getAll() method since you already have every element. Simply use the stream().filter() syntax and collect or map to do whatever e.g.
collection.stream().filter(x -> x..) // do stuff

I think you're looking for Collection.removeIf(Predicate<? super E> filter), although you'll need to negate the predicate logic. Alternately, you can use streams: collection.stream().filter(p).
As for why there isn't a getAll to go along with the other methods, I don't see where the Predicate parameter is coming from, you're not getting "all" if you filter some out. The addAll method adds all the elements, so the analagous method getAll would get all the elements, which is just the collection itself, so it would be redundant.
Also, Collection doesn't even have a get() method in the first place. Maybe you're thinking of List.get(int). I suppose you could have an "All" version like getAll(int[]) that returns the elements at all the given indexes, but that doesn't seem very useful when subList(int, int) already exists.

Related

Why is adding an entry set as parameter to addall method a bad practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
Why is the following code a bad practice and what is the solution for it?
TreeSet<Map.Entry<Integer, Map<String, String>>> sortedtable = new TreeSet<>(new ComparatorByDueDate());
public void sortTable(Map<Integer, Map<String, String>> table){
sortedtable.addAll(table.entrySet());
}
Update: As per Sonar, it is a bad practice. I am asking the question here as the sonar explanation seems confusing.
Java Map.Entry objects are not intended for long term storage. From the docs (emphasis mine),
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
If anyone, for any reason, adds, removes, or modifies any part of the map after the fact, then your TreeSet entries now have undefined behavior. They might still be good, they might get nulled out, they might exhibit some random behavior.
If you want to store a pair of elements, then write a class that has two instance variables. If you're on a new enough Java version, then records are great for this sort of thing.

Telling ArrayList to .add() Itself in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I came across this code. I was wondering if this is possible. As you can see, aList is an ArrayList which .adds() itself.
ArrayList<Object> aList;
aList = new ArrayList<Object>();
aList.add("cat");
aList.add(aList);
aList.add(12);
int size = 0;
Iterator<Object> it = aList.iterator();
while(it.hasNext()) {
it.next();
size++;
}
System.out.print(size);
Yes, it is possible. There are no restrictions on the elements you can add to a ArrayList<Object>.
And you can iterate the list, and do various other things with it.
But don't call toString() on it because you might get a StackOverflowError.
UPDATE - For (at least) Oracle / OpenJDK Java 6 and onwards, the toString() method inherited from AbstractCollection will detect this "self reference" cycle and show it as (this collection) rather than going into an infinite recursive loop.
However:
This is an implementation detail. It is not part of the specification.
I don't know if this applies for all Java versions; i.e. prior to Java 6, and Android versions.
This doesn't apply for 3rd-party List classes that don't extend AbstractCollection. (For them, you would need to check the implementation code to understand what would happen.)
It doesn't apply if the self-reference cycle has more than one "hop"; e.g. list A contains list B, and list B contains list A. In such cases you would get infinite recursion and a StackOverflowError.
So caution is advised.

Is there any alternate way to bring lambda variables outside the lambda loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Result result = ParcelFromDB.getParcelcodes
.stream()
.filter( itr -> itr.getCode().equals(parcelReq.getCode())
.findAny()
.orElse(null);
if(result == null){ ... }
After this, I have to take the existing code which is from the DB and based on that I will proceed on the rest of the logic.
I am unable to take the "itr" value as it is a final variable. Please suggest if there is any alternate way to carry the value of "itr" outside the lambda? I have tried other ways but as per the code base, this is the only way I should do it.
Lamba expression is an anonymous, yet still method, an Anonymous Method.
Variables declared within the scope of method are local to that scope and there's no way to reference them outside of that scope.
itr in the lambda expression represents an item in the stream. One of them (due to your usage of findAny) is returned as the result variable, which you can use later. Instead of just terminating the stream, you could use forEach and operate on all the elements:
ParcelFromDB.getParcelcodes()
.stream()
.filter( itr -> itr.getCode().equals(parcelReq.getCode())
.forEach(itr -> {
// Do something interesting with the item
});

ArrayList.remove at an index does nothing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Basically, when I try to remove an element from an ArrayList by someList.remove(someInteger); it does nothing, the element at that index stays there and the list is unchanged. I'm using java SE's ArrayList implementation. It is ensured that the list has an element at the given index. The boolean returned from the method is false.
There are two methods called remove(), and you're accidentally calling the wrong one.
The boolean returned from the method is false.
If the method is returning a boolean, then it's this overload:
boolean remove(Object o)
and not that one:
E remove(int index)
In other words, it's trying to remove the object by value and not by index (presumably from an ArrayList<Integer> or similar).

Java list default implementation? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
If I declare a new list like this:
List<String> listExample = someFunction();
what list interface implementation will be used?
EDIT: Thanks for the answers so far. What is considered as the clean way to do this, should I always declare list with new?
As Eran commented that totally depends on what someFunction(); returns .Both ArrayList<E> and LinkedList implements List interface .
You can try ,
System.out.println("" + listExample.getClass());
to find out the which has been implemented. From docs,
public final Class<?> getClass()
Returns the runtime class of this Object. The returned Class object is
the object that is locked by static synchronized methods of the
represented class.
Whatever you are building e.g. LinkedList, ArrayList, Vector, Stack in and returning from someFunction() will be implemented with listexample. If you are using List interface reference, it has one benefit, that you can assign any type of object to it (LinkedList, ArrayList, Vector, Stack).
eg if u give
List listExample = new ArrayList();
Then the Object will be created for ArrayList and list is just an instance of listExample.
and you can use getClass() for that listExample to view

Categories