may be too simple groovy question but....please help
i have a list like this:
def ageList =[12,13,23]
i want to get this:
def newAgeList =[age:12,age:13,age:23]
could some one help me out?
thank you so much!
Does this work for you?
def newAgeList = ageList.inject([:]) { map, item -> if (!map['age']) map['age'] = []; map['age'] << item; map }
his would result in: ['age':[12, 13, 23]]
Otherwise, you can get the literal value as something like:
def newAgeList = ageList.collect { "age:$it" }
his would result in: ['age:12', 'age:13', 'age:23']
A third option:
def newAgeList = ageList.collect { ['age':it] }
This would result in: [['age':12], ['age':13], ['age':23]]
Unfortunately, you can't do this as a map like you showed above as map keys must be unique.
Really it all depends on what you are trying to do with the result.
Don't know if this is possible since you want to use the same map key 'age' for three different values. You'll end up overwriting the existing value with a new value.
Related
I have a list object type and I want to sort it by date in ascending order.
First of all I get the resevations that are between these dates and saving it to a new List.
Now I need someway to sort it.
I tried Collections.sort(reservationsByDate) & Collections.sort(reservationsByDate, Collections.reverseSort() , but it didn't produce anything.
I'm kinda new to java so if theres something that im missing please help me implement this.
heres my code:
public List<Reservation> getAllReservationsSortedByDate(LocalDate from, LocalDate to) {
int fromDate = from.getDayOfMonth();
int toDate = to.getDayOfMonth();
ArrayList<Reservation> reservationsByDate = new ArrayList<>();
for (Reservation reservation : reservations) {
if (reservation.getFromDate().getDayOfMonth() >= fromDate && reservation.getToDate().getDayOfMonth() <= toDate) {
reservationsByDate.add(reservation);
}
}
//reservationsByDate needs to be sorted by dates in ascending order...
return reservationsByDate;
}
Thank you for your help.
You are iterating over "reservations". The definition of this field is not shown. If it is empty the result would always be an empty list.
I have a problem in flutter I want to do a search bar and I have a response to an api and I want to show data from server that contains a text from search bar my problem is where method doesn't work with List any ideas ?
Looking at your comment, there is no where method on String types. Instead of the for loop, you want something along these lines:
// Remove the for loop
// for(var i = 0; i <map.length; i++) { _results = jsonDecode(map[i]['address']).where((p)=>p.startsWith(query)).toList(); }
// Do this instead
_results = map.where((item) => item['address'].startsWith(query)).toList();
You should now be able to ditch the for loop.
I'm iterating on a query results computing an array of float values. Now from C++ I want to add it to the originating record, or, if already present, update it.
From Javascript I do something similar to:
db.scraps.find({type: {$exists: 0}}).forEach(function (doc) {
var new_array = []
// fill the elements of new_array from doc fields
doc.new_field = new_array;
db.scraps.save(doc);
}
Seems that this cannot be done with the C++ driver (I'm still running 2.6) except using update. If true, I think I should have to save in an array the pair (OID, new_array) from my query and then iterating on it calling: conn.update("kb.scraps", QUERY("_id" << OID), BSON("new_field" << new_array))
Thanks for your help!
I am new to Pig and still exploring efficient ways to do simple things.
For example, I have a bag of events
{"events":[{"event": ev1}, {"event": ev2}, {"event":ev3}, ....]}
And I want to collapse that as just a tuple, something like
{"events":[ev1, ev2, ev3, ....]}
Is there a way to achieve this in Pig?
I have veen struggling through this for a while, but without much success :(.
Thanks in advance
Looking at your input it seems that your schema is something like:
A: {name:chararray, vals:{(inner_name:chararray, inner_value:chararray)}}
As I mentioned in a comment to your question, actually turning this into an array of nothing but inner_values will be extremely difficult since you don't know how many fields you could potentially have. When you don't know the number of fields you should always try to use a bag in Pig.
Luckily, if you can in fact use a bag for this it is trivial:
-- Project out only inner_value from the bag vals
B = FOREACH A GENERATE name, vals.inner_value ;
Thanks all for informative comments. They helped me.
However, I found I was missing an important feature of a Schema, namely, every field has a key, and a value (a map). So now I achieve what I wanted by writing a UDF converting the bag to a comma separated string of values:
package BagCondenser;
import java.io.IOException;
import java.util.Iterator;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.DataBag;
import org.apache.pig.data.Tuple;
public class BagToStringOfCommaSeparatedSegments
extends EvalFunc<String> {
#Override
public String exec(Tuple input) throws IOException {
// Condensed bag to be returned
String listOfSegmentIds = new String("");
// Cast the input to a bag
Object inputObject = input.get(0);
// Throw error if not bag-able input
if (!(inputObject instanceof DataBag))
throw new IOException("Expected input to be a bag, but got: "
+ inputObject.getClass());
// The input bag
DataBag bag = (DataBag) inputObject;
Iterator it = bag.iterator();
// Collect second fields of each tuple and add to the output bag
while(it.hasNext()) {
// If the return string already had values, append a ','
if ( ! listOfSegmentIds.equals("") )
listOfSegmentIds += ",";
Tuple tuple = (Tuple) it.next();
listOfSegmentIds += tuple.get(0).toString();
}
return listOfSegmentIds;
}
}
I have a
map <wstring,wstring>.
I have inserted pairs like this:
m_Translations.Content().insert(pair<wstring,wstring>(L"rome",L"roma"));
m_Translations.Content().insert(pair<wstring,wstring>(L"water",L"aqua"));
How could I determine the translation for "water" from the map?
In other words: I would like to get the second item from the first.
The search is case-sensitive.
Thank you for the help!
A bit weird question. What about the default way of accessing a map with operator[]?
wstring aqua = m_Translations.Content()[L"water"];
In case you are not sure whether a translation exists or not, you can check it with the find method:
const auto& dict = m_Translations.Content();
auto pAqua = dict.find(L"water");
if (pAqua != dict.end())
{
// Found it!
}
else
{
// Not there...
}
You can use operator[] available on std::map.
For example:
map<wstring, wstring> myMap = m_Translations.Content();
myMap.insert(pair<wstring, wstring>(L"rome", L"roma"));
myMap.insert(pair<wstring, wstring>(L"water", L"aqua"));
// waterText value would be 'aqua'
wstring waterText = myMap[L"water"];