List from List Streams JAVA8 - list

I need go through a list(class A) from lists(classB). I want to use streams JAVA8, but go through the second list i lose the reference from first list
class A {
Collection<B> listB ;
String x;
// Some other variables
}
class B {
String y;
// Some other variables
}
// List object A
Collection<class A> listA;
listA.stream()
.filter(a -> a.getListaB() != null)
.flatMap(a -> a.getListB().stream())
.forEach(b -> {
// Here lose reference object A
// I need something like a.getX()
// I need too use something like b.getY(), use both lists
});
The error is "cannot find simbol variable a" I understand the error, There is any solutions use streams and not foreach or for loop?

Because you don't nest the second stream to the first one but you flatten it :
.flatMap(a -> a.getListB().stream())
So finally after this statement you get simply a stream<B> of all elements of Lists of B.
To solve you requirement, nest the stream and use forEach() instead of flatMap() as here you don't want to transform anything but you want to apply a Consumer :
Collection<A> listA = ...;
listA.stream()
.filter(a -> a.getListaB() != null)
.forEach(a -> a.getListB().stream()
.forEach(b -> {
// a and b are usable now
})
);

Related

Construct lists from existing lists at compile time

I have a global list of items (each with a few properties) in a module of my program. It's immutable and statically defined in the code, so no worries there.
For instance let's say I have vegetables, which are just an alias defining them to an immutable tuple with name (string), code (ubyte) and price (ushort).
I'd like to be able to access those either by name or by code ; so I thought since the list of vegetables is known at compile-time, I could probably construct associative arrays with references to these vegetables (so string=>vegetable and ubyte=>vegetable)
Here's the kind of thing I am trying to achieve :
static struct instructions
{
// list of Veggies
immutable instr[] list = [
Veggie("Potato" , 0xD0, 2),
Veggie("Carrot" , 0xFE, 5),
];
// genByCode and genByName being pure functions that get CTFE'd
// and return the desired associative array
immutable instr[ubyte] byCode = genByCode(list);
immutable instr[string] byName = genByName(list);
// overloaded function returns the right Veggie
instr get(string name) const
{ return byName[name]; }
instr get(ubyte code) const
{ return byCode[code]; }
}
With those generator functions (separated for clarity) of the form
pure instr[ubyte] genByCode(immutable Veggie[] list)
{
instr[ubyte] res;
foreach (i ; list)
res[i.code] = i;
return res;
}
I spent quite some time messing around but I couldn't it to work. Of course it would be trivial to construct at runtime, but clearly it should be possible to do it at compile time.
At first I thought it was an issue of mutability, so I tried marking everything (vegetables and vegetable lists) as immutable (as they should be anyway), but then I ran into issues which I think regard immutable tuples, and feel too lost to keep going.
Could I get help from someone with a clearer overview of the mechanisms at play here ? Thanks !
The data is already there, no need to construct a compile-time associative array.
Just iterate over it statically:
static auto get(int code)(){
static foreach(veggie; list)
static if(veggie.code == code)
return veggie;
}
...
void main(){
writeln(instructions.get!0xD0);
}
It may be slower than access through a hash map, but that's the life of CTFE.
To make sure it evaluates at compile time, you can use this:
template get(int code){
static foreach(veggie; list)
static if(veggie.code == code)
alias get = veggie;
}

Antlr4 c++ visitor API

I am using Antlr4's C++ visitor api to traverse a parse tree. However, I'm struggling to get it functioning correctly. Namely, I'm not sure how to use the visitChildren(ParseTree *tree) call.
I'm given the context for each rule that I have defined. And I can traverse the tree using the contexts: context->accept[RuleContext]([RuleContext]* rule)
However, when I use those I continually visit the same node multiple times.
For instance:
program:
: nameRule
dateRule
( statements )*
EOF
;
nameRule
: NAME IDENTIFIER ;
dateRule
: DATE IDENTIFIER ;
statements:
: statementX
| statementY
| statementZ
;
statementX:
: // do something here
statementY:
: // do something here
statementZ:
: // do something here
IDENTIFIER, DATE, and NAME are terminals.
I build the Antlr parsing structure by the following:
void Parser::parse() {
ifstream file(FLAGS_c, ifstream::binary);
// Convert the file into ANTLR's format.
ANTLRInputStream stream = ANTLRInputStream(file);
// Give the input to the lexer.
MyLexer lexer = new MyLexer(&stream);
// Generate the tokens.
CommonTokenStream tokens(lexer);
file.close();
tokens.fill();
// Create the translation that will parse the input.
MyParser parser = new MyParser(&tokens);
parser->setBuildParseTree(true);
MyParser::ProgramContext *tree = parser->program();
auto *visitor = new MyVisitor();
visitor->visitProgram(tree);
}
So when I try to traverse this it looks similar to this, the class MyVisitor extends MyParserVisitor. MyVisitor is the visitor class I use to traverse the generated tree.
Any MyVisitor::visitProgram(ParserVisitor::ProgramContext *context) {
this->visitNameRule(context->nameRule());
this->visitDateRule(context->dateRule());
if (!this->statements.empty()) {
for (auto &it : this->statements) {
this->visitStatements(it);
}
}
return Any(context);
}
// Omitting name and date rules.
Any MyVisitor::visitStatements(ParserVisitor::StatementContext *context) {
this->visitStatementX(context->statementX());
this->visitStatementY(context->statementY());
this->visitStatementZ(context->statementZ());
return Any(context);
}
In this case, statements X, Y, and Z will be visited every time statements is visited. Even if they aren't present in the input program.
Is this the correct way to use this? If it isn't, then I assume the visitChildren(ParseTree *tree) is the correct api to use at each visitor function. But I don't understand how to get access to the ParseTree data structure from the *Context.
This question is not directly related to the C++ visitor, but a general visitor problem in ANTLR4. What you are doing is to shortcut the visitor walk in a way you are not intended to do. Don't explicitly visit the certain sub trees manually, but instead call the super implementation to let it do for you and collect the result in individual visitStatementXXX functions. Look at this implementation of a (very simple) expression evaluator, used in a unit test (written in C++). Here's a partial copy to demonstrate the principle:
class EvalParseVisitor : public MySQLParserBaseVisitor {
public:
std::vector<EvalValue> results; // One entry for each select item.
bool asBool(EvalValue in) {
if (!in.isNullType() && in.number != 0)
return true;
return false;
};
virtual Any visitSelectItem(MySQLParser::SelectItemContext *context) override {
Any result = visitChildren(context);
results.push_back(result.as<EvalValue>());
return result;
}
virtual Any visitExprNot(MySQLParser::ExprNotContext *context) override {
EvalValue value = visit(context->expr());
switch (value.type) {
case EvalValue::Null:
return EvalValue::fromNotNull();
case EvalValue::NotNull:
return EvalValue::fromNull();
default:
return EvalValue::fromBool(!asBool(value));
}
}
virtual Any visitExprAnd(MySQLParser::ExprAndContext *context) override {
EvalValue left = visit(context->expr(0));
EvalValue right = visit(context->expr(1));
if (left.isNullType() || right.isNullType())
return EvalValue::fromNull();
return EvalValue::fromBool(asBool(left) && asBool(right));
return visitChildren(context);
}
...
The essential part is the call to visit() which in turn iterates over the child nodes of the given context tree and triggers only visitor functions for elements that actually exist.

Kotlin: How to work with List casts: Unchecked Cast: kotlin.collections.List<Kotlin.Any?> to kotlin.colletions.List<Waypoint>

I want to write a function that returns every item in a List that is not the first or the last item (a via point). The function gets a generic List<*> as input. A result should only be returned if the elements of the list are of the type Waypoint:
fun getViaPoints(list: List<*>): List<Waypoint>? {
list.forEach { if(it !is Waypoint ) return null }
val waypointList = list as? List<Waypoint> ?: return null
return waypointList.filter{ waypointList.indexOf(it) != 0 && waypointList.indexOf(it) != waypointList.lastIndex}
}
When casting the List<*> to List<Waypoint>, I get the warning:
Unchecked Cast: kotlin.collections.List
to kotlin.colletions.List
I can't figure out a way to implement it otherwise. What's the right way to implement this function without this warning?
In Kotlin, there's no way to check the generic parameters at runtime in general case (like just checking the items of a List<T>, which is only a special case), so casting a generic type to another with different generic parameters will raise a warning unless the cast lies within variance bounds.
There are different solutions, however:
You have checked the type and you are quite sure that the cast is safe. Given that, you can suppress the warning with #Suppress("UNCHECKED_CAST").
#Suppress("UNCHECKED_CAST")
val waypointList = list as? List<Waypoint> ?: return null
Use .filterIsInstance<T>() function, which checks the item types and returns a list with the items of the passed type:
val waypointList: List<Waypoint> = list.filterIsInstance<Waypoint>()
if (waypointList.size != list.size)
return null
or the same in one statement:
val waypointList = list.filterIsInstance<Waypoint>()
.apply { if (size != list.size) return null }
This will create a new list of the desired type (thus avoiding unchecked cast inside), introducing a little overhead, but in the same time it saves you from iterating through the list and checking the types (in list.foreach { ... } line), so it won't be noticeable.
Write a utility function that checks the type and returns the same list if the type is correct, thus encapsulating the cast (still unchecked from the compiler's point of view) inside it:
#Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> List<*>.checkItemsAre() =
if (all { it is T })
this as List<T>
else null
With the usage:
val waypointList = list.checkItemsAre<Waypoint>() ?: return null
To improve #hotkey's answer here's my solution:
val waypointList = list.filterIsInstance<Waypoint>().takeIf { it.size == list.size }
This gives you the List<Waypoint> if all the items can be casted, null otherwise.
In case of generic classes casts cannot be checked because type information is erased in runtime. But you check that all objects in the list are Waypoints so you can just suppress the warning with #Suppress("UNCHECKED_CAST").
To avoid such warnings you have to pass a List of objects convertible to Waypoint. When you're using * but trying to access this list as a typed list you'll always need a cast and this cast will be unchecked.
I made a little variation to #hotkey answer when used to check Serializable to List objects :
#Suppress("UNCHECKED_CAST")
inline fun <reified T : Any> Serializable.checkSerializableIsListOf() =
if (this is List<*> && this.all { it is T })
this as List<T>
else null
Instead of
myGenericList.filter { it is AbstractRobotTurn } as List<AbstractRobotTurn>
I like doing
myGenericList.filter { it is AbstractRobotTurn }.map { it as AbstractRobotTurn }
Not sure how performant this is, but no warnings at least.
Kotlin ensures type safety for operations involving generics at compile time, while, at runtime, instances of generic types don't hold information about their actual type arguments. For example, List is erased to just List<*>. In general, there is no way to check whether an instance belongs to a generic type with certain type arguments at runtime.
https://kotlinlang.org/docs/typecasts.html#type-erasure-and-generic-type-checks

modifying the list of lists

there is a structure like this:
std::list<std::list<std::string>> data;
I need to go throu the top level list and append internal lists against some criteria. something like this:
std::for_each(data.begin(), data.end(),
[<some variable required for the logic>]
(const std::list<std::string>& int_list) {
if(...)
int_list.push_back(...);
});
you see this code is not valid, because for_each can't modify the sequence.
what would you recommend me to perform what I need (without modifying initial data structure)?
You can use a C++11 ranged based for loops like:
std::list<std::list<std::string>> data;
for (auto & e : data)
{
if (some_condition)
e.push_back(some_data)
}

How to use a template function with multiple parameters in a template class C++

I'm trying to work on a question for a project in class where our data structures and methods are already pre-defined. It's my job to implement some functions that use these templates.
For example, I'm supposed to create a follows function, that does this: if I did follows(q) where q = {"h", "e", "l", "l", "o", "w", "r"} and q is of type ArrayQueue, it would create an ArrayMap that holds a single queue value as a key and a set of values that is next to that queue value.
If I looked inside the map, it would look like this:
Key -> Set Containing the Values
h -> set[e]
e -> set[l]
l -> set[l, o]
o -> set[w]
w -> set[r]
Now, I'm supposed to implement this function by using this template signature:
template<class T>
ics::ArrayMap<T,ics::ArraySet<T>> follows (const ics::ArrayQueue<T>& q)
{
}
Although I understand the general logic behind how I would do this, I do need one thing: to be able to access and update the second parameter in the returned ArrayMap, which is ics::ArraySet<T>
So how would I call this ArraySet as a variable to do modifications on?
From your description it sounds like you should be able to do the following:
ics::ArraySet<T>& followers = the_array_map[x];
Assuming that you have a variable the_array_map which holds the follower map that you are constructing (and returning from the function).
Now you can update followers by appending the desired element to it.