I have a situation where I want to remove duplicates from a collection (list) and then join them.
I wanted to make an extension for Joiner, but it is impossible as all constructors are private.
Here's a code snippet of what we did:
Collection<String> tokens = newArrayList();
for (int i = 0; i < numOfFoundTitles; i++) {
if (!tokens.contains(titlesInRange.get(i).titleAsTokens)) {
tokens.add(titlesInRange.get(i).getTitleAsTokens());
}
}
return titleTokensJoiner.join(tokens);
Any suggestions?
I thought about Function / Predicate, but they are not suitable there.
Thanks
Eyal
return titleTokensJoiner.join(ImmutableSet.copyOf(tokens));
Short, sweet, and correct. ImmutableSet preserves the order of the original input, but ignores repeated occurrences of an element after the first occurrence.
Related
I'm trying to loop through two lists at the same time
For example
List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for(var chapter in A) // This would itreate through only first list (A), How can I iterate through both list
children: [
Text(chapter);
Text(paragraph);
]
I need to iterate through both lists at the same time in "for" loop.
Here is the code:
List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (int i = 0; i < A.length; i++) {
print ("${A[i]}");
print ("${B[i]}");
}
Let me know if this does not help.
final c = zip([a, b]).map((item) => Foo(item[0], item[1])).toList();
I went along with Randal Schwartz's note about IterableZip. Note that I was not able to find any zip mentioned by Gbenga, and also note that package:collection/iterable_zip.dart is deprecated, you'd need to import simply the collection.dart, like so:
import 'package:collection/collection.dart';
final A = ['Chapter 1','Chapter 2','Chapter 3'];
final B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (final pairs in IterableZip([A, B])) {
print(pairs[0]);
print(pairs[1]);
}
Some more notes:
final A and final B variables will be typed List<String> lists, I disadvise dynamic List A.
I have not specified template type for IterableZip, but in some cases (in a complex case where I used it) you may need to explicitly type it like IterableZip<String>, so in the loop you can more conveniently access the members. In this simple case the compiler/interpreter can infer the type easily.
Some other answers in other StackOverflow issues mention quiver, but unless you need it for some other features you don't have to add another extra package dependency to your project. The standard collection package has this IterableZip
I am getting a list of maps via an api. Now i want to get the sum of all values of a specific key in the maps. Can anyone help me with that?
A simple for-loop should do the job
Since you have not provided any code, I am making a lot assumptions here, but I hope you get the idea.
List<Map<String, int>> mapList;
// Now add members to list
int sum = 0; // contains the sum of `field` values of all members
for(int i=0; i<mapList.length; i++) {
sum += mapList[i]['field'];
}
Given:
class Point {
int x;
int y;
}
List<Point> points;
How can I check that property x in a list of Points is greather than a value? I aim something similar to:
assertThat(points).extracting("x").isGreatherThan(20)
However I can't find 'isGreatherThan' after 'extracting'
Update
I don't aim writing custom conditions for this kind of value checking, as assertj already has methods for checking numbers.
Thanks
You can use filteredOn as it supports java 8 Predicate, e.g:
assertThat(listOfPoints).filteredOn(p -> p.x > 20).isNotEmpty();
If you want to do more complex stuff, using Condition is the way to go, in AssertJ 3.x they are simpler to write, rewriting Florian Schaetz example:
Condition<Integer> greaterThan20 = new Condition<>(v -> v.intValue() > 20, "greater than 20");
You can try this one...
.extracting( "x", Integer.class ).areAtLeast( 1, greaterThan20 );
Of course you'll have to write the condition yourself, something like...
final Condition<Integer> greaterThan20 = new Condition<Integer>("greater than 20") {
#Override
public boolean matches(Integer value) {
return value.intValue() > 20;
}
};
In Java 8 you can do something like this:
assertThat(listOfPoints.stream().filter(p->p.x > 20).toArray()).hasSameSizeAs(listOfPoints);
That's for the case where you want ALL points to have x > 20.
To verify that there's at least one (as in Florian Schaetz's answer):
assertThat(listOfPoints.stream().filter(p->p.x > 20).toArray()).isNotEmpty();
In a graph model I have a vertex called timeCategory with childs year-vertices, month-vertices and day-vertices. I am able to identify a year with the edge-label with IS_YEAR, a month with IS_MONTH, etc.
I want to do a query that returns all vertices of a given year range similarly to the following code:
GremlinPipeline yearPipe = new GremlinPipeline(timeCategory).out("IS_YEAR").property("year")
.filter(new PipeFunction<Integer, Boolean>() {
public Boolean compute(Integer i)
{
return i < 2013 && i >= 2011;
}
});
for(Object v : yearPipe) {
//v is an Integer, but i need the vertex
System.out.println(v);
}
... this works great for printing all property-values (the years as integers), but what I need is a list of all VERTICES which year-properties are between a given range.
My second question is about making a intersection from values in pipes.
For example: I have three pipes, a yearpipe, a monthpipe, and daypipe, and the pipes containg vertices that identifies a year, month, or day.
Is it possible to get all outgoing vertices to one special date...
Semi-Code: allVertices2012-01-01 = yearpipe.out() AND monthpipe.out() AND daypipe.out
sure, i can do some compares in some for-each-loops, but i wanted to know if there is a (simple) gremlin - way to do it better.
There are two solutions to your problem. Here it is in Gremlin-Groovy:
timeCategory.out('IS_YEAR').filter{year = it.getProperty('year'); year < 2013 && year >= 2011}
-OR-
timeCategory.out('IS_YEAR').property('year').filter{it < 2013 && it >= 2011}.back(1)
Here is your answer in Gremlin-Java code (for the second representation above):
GremlinPipeline yearPipe = new GremlinPipeline(timeCategory).out("IS_YEAR").property("year")
.filter(new PipeFunction<Integer, Boolean>() {
public Boolean compute(Integer i)
{
if(i<2013 && i>=2011)
return true;
else
return false;
}
}).back(1);
Okay after some short-tutorials reading, I figuered out that the param on .back(x) should be 2... so, with .back(2) you will get your vertices.
btw. the examples provided at http://markorodriguez.com are much better for a gremlin quick start then these on github-wiki, in my opinion.
To my second question: I found out there is a topic on gremling-users, that describes pretty well my problem:
http://groups.google.com/group/gremlin-users/browse_thread/thread/d245b1a25ac1fac8/514931b1e3bf9e30?lnk=gst&q=intersect#514931b1e3bf9e30
Consider the below program
private static bool CheckFactorPresent(List<FactorReturn> factorReturnCol)
{
bool IsPresent = true;
StringBuilder sb = new StringBuilder();
//Get the exposure names from Exposure list.
//Since this will remain same , so it has been done outside the loop
List<string> lstExposureName = (from item in Exposures
select item.ExposureName).ToList<string>();
foreach (FactorReturn fr in factorReturnCol)
{
//Build the factor names from the ReturnCollection dictionary
List<string> lstFactorNames = fr.ReturnCollection.Keys.ToList<string>();
//Check if all the Factor Names are present in ExposureName list
List<string> result = lstFactorNames.Except(lstExposureName).ToList();
if (result.Count() > 0)
{
result.ForEach(i =>
{
IsPresent = false;
sb.AppendLine("Factor" + i + "is not present for week no: " + fr.WeekNo.ToString());
});
}
}
return IsPresent;
}
Basically I am checking if all the FactorNames[lstFactorNames] are present in
ExposureNames[lstExposureName] list by using lstFactorNames.Except(lstExposureName).
And then by using the Count() function(if count() > 0), I am writing the error
messages to the String Builder(sb)
I am sure that someone can definitely write a better implementation than the one presented.
And I am looking forward for the same to learn something new from that program.
I am using c#3.0 and dotnet framework 3.5
Thanks
Save for some naming convention issues, I'd say that looks fine (for what I can figure out without seeing the rest of the code, or the purpose in the effort. The naming conventions though, need some work. A sporadic mix of ntnHungarian, PascalCase, camelCase, and abbrv is a little disorienting. Try just naming your local variables camelCase exclusively and things will look a lot better. Best of luck to you - things are looking good so far!
- EDIT -
Also, you can clean up the iteration at the end by just running a simple foreach:
...
foreach (var except in result)
{
isPresent = false;
builder.AppendFormat("Factor{0} is not present for week no: {1}\r\n", except, fr.WeekNo);
}
...