Iteration of two identical Set using Java Streams [duplicate] - java-stream

This question already has answers here:
Difference between `Optional.orElse()` and `Optional.orElseGet()`
(9 answers)
When I need to use Optional.orElseGet() over Optional.orElse()
(3 answers)
Closed 2 years ago.
I have two HashSets with same type of objects. My search criteria is like, search in first set and if not present then search in another set. I had tried with Stream layer with following steps as given below
Set<MyObject> firstSet = new HashSet<>();
Set<MyObject> secondSet = new HashSet<>();
and these two sets are having some values.
Predicate<MyObject> match = myObject -> StringUtils.equals(myValue, myObject.getMyValue());
firstSet.values().stream().filter(match).findFirst()
.orElse(secondSet.values().stream().filter(match)
.findFirst().orElseThrow(()-> new MyException()));
My matching object is in First Set and i have tried to get it by manually and i got it... but using the above iteration, i always get the exception even when the first set has the matched object. Kindly correct me.. thanks is advance.

Your problem is that you are not using Optional.orElse as expected.
When you use Optional.orElse, its parameter is evaluated eagerly. This means that your second set is being searched first, to resolve the parameter of your first set's Optional.orElse.
Instead, use Optional.orElseGet, which receives a Supplier that is evaluated lazily:
firstSet.stream()
.filter(match)
.findFirst()
.orElseGet(() -> secondSet.stream()
.filter(match)
.findFirst()
.orElseThrow(()-> new MyException()));
EDIT: As suggested by Holger in the comments, there is an easier way:
Stream.of(firstSet, secondSet)
.flatMap(Set::stream)
.filter(match)
.findFirst()
.orElseThrow(MyException::new);
Streaming the sets first and then calling flatMap ensures that elements of the first set will all appear before elements of the second set.

Related

Newly added line item is getting removed after making changes in data which is already bound to sap.m.Table [duplicate]

This question already has answers here:
Add a New Item to a Table / List
(2 answers)
Closed 17 days ago.
We have to perform edit functionality where we have to take two scenarios into consideration:
Make changes in existing entries.
Add new entries and update the old entries.
In the 2nd scenario, when we are trying to add a new entry, it is getting added to sap.m.Table but if we make any change in the old entry then the newly added line item is disappearing.
let oContextLineItemEntry = oLineItmTab.getModel().createEntry("/EntityName", {
properties: NewLineItem,
});
let oTmp = oLineItmTab.getBindingInfo("items").template,
oItem = oTmp.clone();
oItem.setBindingContext(oContextLineItemEntry);
oLineItmTab.addItem(oItem);
Here NewLineItem is an object which I want to add and it is blank. It is initiated like below:
NewLineItem = oLineItmTab.getItems()[0].getBindingContext().getObject();
After this, I have removed all the values of the objects attribute.
I tried with OData V2 OneWay binding, but it didn't work.
I saw framework behavior is triggering this interaction
onChange started
onChange completed
I went through these questions on SAP Community:
https://answers.sap.com/questions/699607/newly-added-table-row-disappearing-when-changing-p.html
https://answers.sap.com/questions/13305104/ui5-controls-and-onchange-event-in-a-sapuitabletab.html
After you bind an aggregation it will be managed by the data binding. Therefore you should not try to modify the aggregations. Instead, do the changes in the model and then the aggregation should be updated according to data in the model. e.g.
let newRow = {key: "_your_unique_id_", value: ""};
let model = table.getModel();
let tableData = model.getProperty("/tableEntityName");
tableData.unshift(newRow);
model.setProperty("/tableEntityName", tableData);
Besides that consider to set the growing property of the table to true.
We had raised an OSS note for this issue to which SAP replied, this is not and issue with UI control but the way to use it.
Basically we are not supposed to add new entries when OData binding is being used.

Convert from Set to List in Dart / Flutter?

I have a Set of type Set<WordPair> & I want to convert it to List of type List<String> because I want to save it using SharedPreferences API in Flutter
Currently, my state looks like
final Set<WordPair> _saved = Set<WordPair>();
Now I want to save the _saved variable into SharedPreferences
If I do, prefs.setStringList('saved', _saved.toList()); it gives me compilation error like
[dart] The argument type 'Set' can't be assigned to the parameter type 'List'. [argument_type_not_assignable]
How do I store complete _saved variable in SharedPreferences?
The reason you are unable to save it in the Preferences even after converting it into a list is that you are trying to save StringList (prefs.setStringList) whereas your set is of type WordPair
A workaround for that could be,
prefs.setStringList('saved', _saved.map((WordPair wordPairItem) => wordPairItem.toString()).toList());
i.e converting each item into String and then save it as StringList
To your follow-up question in the comments:
how do I convert from List<String> to Set<WordPair> in initState? As there is no .toWordPair() & wrapping up takes 2 args so Idk how to do it?
As per documentation, WordPair is Representation of a combination of 2 words, first and second. Therefore, you can break the String into two substrings and pass those 2 substrings in the respective argument positions.
[Update] (solution proposed by the Author of the follow-up question)
The solution can be found at here

How to create an empty Results<T> object?

I'm trying to create a MutableProperty which holds a Results received from Realm.objects(_:).
To create the property I need to give it an initial value; hence an 'empty' Results.
I've tried creating one using:
var someThings = Results<SomeObject>()
MutableProperty(someThings)
But the compiler gives me the error: Cannot invoke initializer for type 'Results<SomeObject>' with no arguments.
While I understand the error, I'm not really sure how to create a Results object in this context.
Looking at the source of Results I couldn't find an init either.
So my question is; how can I create a Results myself to use in a MutableProperty?
Edit:
I've seen this question...but that doesn't really help (unless I'm going to create a "wrapper" for the MutableProperty or something).
With help of the comments on my OP; I created a mutable property with an empty set of results by fetching objects with an 'invalid' filter.
E.g. MutableProperty(realm.objects(SomeObject.self).filer("EMPTY SET")).

How to update value in angular ui typeahead directive if no matching option is found

I've an array of objects containing title and salary which is used in typeahead directive.
I display department name and get entire object as value.
If none of the options match, I want user entered string to be converted to object still. Is there any way to update that?
This answer is pretty late, but I would just use ng-blur (to trap the end of the users input) along with a variable bound to typeahead-no-results. Then test if the variable is true in the method bound to ng-blur, and, if so, make an object out of the String supplied by the user and push it to your data source. Simple example found here.

Return Filtered Module in DXL

I need to make a filter in certain Module and get the filtered items and loop over them and do some kind of operation.
problem is filtering isn't done , something is wrong as follows :
Filter SwTest = includes(attribute "aVerificationStrategy" ,"SwTest")
Filter Implemented = (attribute "aObjectStatus" < "inReview")
Filter SwTestReqsCASTLE = SwTest && Implemented
Module m = srs_doc
set(m, SwTestReqsCASTLE, accepted , rejected)
filtering on OR ApplyFiltering(m) , i tried each as don't know difference !
so what is wrong ?
Before I answer your main question, first allow me to answer your implied question about the difference between "filtering on" and "ApplyFiltering(m)". The difference is that "filtering on" displays the current filter in the module window, meaning that objects are either shown or hidden depending on the filter. "ApplyFiltering(m)" applies the current filter settings to the module explorer (the area to the left of your objects that shows the hierarchy). "filtering on" shows and hides objects and "ApplyFiltering(m)" reflects the status of those objects in the module explorer.
As for why your filters are not being applied, there could be several reasons:
It is good practice to turn filtering off before you start setting filters. Add the line "filtering off" before the rest of your code.
Your "Implemented" filter is not defined properly. DOORS will see "inReview" as a string, and it will perform a direct comparison with the string value of your "aObjectStatus" attribute in order to determine if an object is accepted or rejected. Is this what you intended?
What type of variable is srs_doc? If it's a string then you need to
call read(), share(), or edit() in order to actually open the
module. If it is a module variable then that line is correct.
I am assuming that "accepted" and "rejected" are integers, but if they are not previously declared then they need to be.
Based on the first paragraph in my comment, your last line should read "filtering on"
Is the module you want to filter being displayed? I realize this is probably obvious, but I have made this mistake before so I thought I should mention it. A filter cannot be applied on a module that is not currently being displayed.
As a side note, you can compound your SwTest and Implemented filters without creating extra Filter variables as follows:
Filter SwTestReqsCASTLE = includes(attribute "aVerificationStrategy", "SwTest") && (attribute "aObjectStatus" < "inReview")
I hope some of that helps! Good luck, and let me know if none of the above solves your problem.

Resources