I have a linked hash list of some DTO that contains name (String) and isActive (boolean) properties. I need to iterate over all of them from first to last and check, if any of members have false value in isActive. When I find this element, I need to cut off this element and the rest of list and return just elements before this one.
I would like to use java streams to solve this problem.
I've tried to use stream and filter elements via predicate to check if element is active but that does not match the logic I want. As I said, I need to find first element that is inActive and cut it and everything after from the list.
If we have this list of ElementDto in LinkedHashSet<>
0 - name:test, isActive:true
1 - name:test2, isActive:true
2 - name:inActive, isActive:false
3 - name:activeAfterInactive, isActive:true
The expected output would be list with elements 0,1
The following should work for any ordered collection:
elementCollection.stream().takeWhile(el -> el.isActive())...
Related
so i have an array list that contains strings such as:
ArrayList<String> list = new ArrayList<>();
list.add("bookshelf");
list.add("bookstore");
list.add("library");
list.add("pencil");
Now i wanna search and remove all the strings in the arraylist that contain the word "book" in them. As far as i understand list.remove("book"); will only search for the particular string "book" and not the strings that contain the word "book". How can i solve this?
You can use removeIf like this:
list.removeIf(s -> s.contains("book"));
Note: this answers applies to Java version 7 and below (of course that it will work for higher versions as well but YCF_L's answer is simpler to implement in versions 8 and above).
The requirement is to iterate the list, check every element, and if it answers a certain condition: remove it.
Since this is the case we fall into a risky scenario where we modify the list while iterating it which is problematic because when we remove an element in the list its size changes.
In order to work around this problem we can iterate the list by index from the last element and back until the first one, this way, removing an element at index n will not effect accessing any element at index < n.
I'll leave the implementation details to you in order not to "spoon feed" and destroy your exercise :)
So, I have a 2d array (really, a List of Lists) that I need to squish down and remove any duplicates, but only for a specific field.
The basic layout is a list of Matches, with each Match having an ID number and a date. I need to remove all duplicates such that each ID only appears once. If an ID appears multiple times in the List of Matches, then I want to take the Match with the most recent date.
My current solution has me taking the List of Matches, adding it to a HashSet, and then converting that back to an ArrayList. However all that does is remove any exact Match duplicates, which still leaves me with the same ID appearing multiple times if they have different dates.
Set<Match> deDupedMatches = new HashSet<Match>();
deDupedMatches.addAll(originalListOfMatches);
List<Match> finalList = new ArrayList<Match>(deDupedMatches)
If my original data coming in is
{(1, 1-1-1999),(1, 2-2-1999),(1, 1-1-1999),(2, 3-3-2000)}
then what I get back is
{(1, 1-1-1999),(1, 2-2-1999),(2, 3-3-2000)}
But what I am really looking for is a solution that would give me
{(1, 2-2-1999),(2, 3-3-2000)}
I had some vague idea of hashing the original list in the same basic way, but only using the IDs. Basically I would end up with "buckets" based on the ID that I could iterate over, and any bucket that had more than one Match in it I could choose the correct one for. The thing that is hanging me up is the actual hashing. I am just not sure how or if I can get the Matches broken up in the way that I am thinking of.
If I understand your question correctly you want to take distinct IDs from a list with the latest date by which it occurs.
Because your Match is a class it is not as easy to compare with each other because of the fields not being looked at by Set.
What I would do to get around this problem is use a HashMap which allows distinct keys and values to be linked.
Keys cannot be repeated, values can.
I would do something like this while looping through:
if(map.putIfAbsent(match.getID(), match) != null &&
map.get(match.getID()).getDate() < match.getDate()){
map.replace(match.getID(),match);
}
So what that does is it loops through your matches.
Put the current Match with its ID in if that ID doesn't exist yet.
.putIfAbsent returns the old value which is null if it did not exist.
You then check if there was an item in the map at that ID using the putIfAbsent (2 birds with one stone).
after that it is safe to compare the two dates (one in map and one from iteration - the < is an exams for your comparison method)
if the new one is later then replace the current Match.
And finally in order to get your list you use .getValues()
This will remove duplicate IDs and leave only the latest ones.
Apologies for typos or code errors, this was done on a phone. Please notify me of any errors in the comments.
Java 7 does not have the .putIfAbsent and .replace functionality, but they can be substitued for .contains and .put
Do I have to search for the node as a stack or queue, and when I find it set the data that the node returns equal to local variables?
Or is there a way of calling a known position in the list, like how you can with an array.
Visually what I'm asking here is:
So how Arrays work like this:
ArrayofStrings[Postion] returns String located at Position
Is there a way to do the same with a Linked List like this?
SinglyLinkedList(Node) returns Multiple(string) Data(double)
I'm guessing I have to search the list for the node, but I wanted to make sure there wasn't an easier way to do this.
LinkedLists pros and cons
pros
traversing
adding or removing anywhere because you just have to
change two pointers(reference in Java)
cons
get by index because it will traverse through elements until it finds the specific one (doubly linked list may be a little faster because if you have total
count you can start from beginning or end depending on the index ie
if there are 100 elements and you want to goto 75 you can start from
the other end which will only require to traverse 25 elements)
Arrays pros and cons.
pros
traversing (even subset),
adding data at the end
getting element from a specific location.
cons
If you add or remove element from the middle it will shift all the elements after that location.
All lists in java provide an implementation of get, which returns the n'th element in list.
I'm using List of strings and trying to insert strings to specified indices using
lst.add(index, string);
(lst is of type `List`).
First I initiated the list to 20 spots of null (now lst.size() = 20).
When I'm inserting the first string it's all good : lst.add(1,"Hi") and the list:
[null,Hi,null,...null], lst.size() is still 20
But when I try to add the next strings it extends the list. I mean if I use lst.add(0,"Bye") the list looks like this: [Bye,null,Hi,null,null,...null] and lst.size() = 21 ! Why ?
it added the string "Bye" before the null though it should have replaced it
Any help ? thanks :)
The add() method inserts into the list.
From JavaDoc:
Inserts the specified element at the specified position in this list
(optional operation). Shifts the element currently at that position
(if any) and any subsequent elements to the right (adds one to their
indices).
You want to use the set() method instead.
When you do 'add' it is actually an insert to a list - therefore you would have 21 elements instead of 20 after the add.
A list can be thought as a resizeable array. You shouldn't need to initialise an array with 20 nulls inserted in it.
If you want total control on the size of the collection, simply use array instead of list (String[] instead of List<String>)
What I have to do to check I have got list of data or one argument?
I have got this in code software and he show "yes" if argument 1 but if I have got list I have got empty place. I would like to make If which can accept only one agument but no list.
System.out.println(doc.getDocumentElement().getChildNodes().item(t).getNodeName());
System.out.println(doc.getDocumentElement().getChildNodes().item(t).getLastChild().getNodeValue());
Output (because car have list of nodes and If some element have list not one value I don`t want to show this element for example "car"):
Adam
yes
car
List:
<car>
<window>yes</window>
<door>yes</door>
</car>
1 argument
<Adam>yes</Adam>
Just check the length of the list.
And you probably don't want all kinds of child nodes, rather just child elements. Try
doc.getDocumentElement().getElementsByTagName("*")
instead.