how to filter list object by using stream map filter in java - list

i want to filter a list of student in java. I have a student class in kotlin like this.
class Student(
var id: String? = null,
var firstName: String? = null,
var lastName: String? = null
) {
constructor(entity: StudentCourse?): this() {
if (entity != null) {
this.id = entity.id.id
this.name = entity.name
}
}
}
class StudentCourse (#EmbeddedId open var id: StudentCourseId) {
constructor() : this(StudentCourseId())
open var name: Boolean? = null
}
#Embeddable
open class StudentCourseId: Serializable {
open var id: String? = null
open var deptName: String? = null
}
this is the list i want to filter :
var students: List<Student> = listOf(
Student("14adbv45", "dan", "GEG"),
Student("96adbv42","Bob", "Bowyer"),
Student("30adbv45","Emily", "Eden")
)
I do this
List<students> studentListContainsFirstNameBob = students.stream()
.map(StudentCourse)
.filter(e -> e.getFirstName.equals("Bob"))
.flatMap(List::stream);
but it doesn't work.
How can i do it please

There are multiple issues in your code.
For example in this part:
constructor(entity: StudentCourse?): this() {
if (entity != null) {
this.id = entity.id.id
this.name = entity.name
}
}
The entity.name refers to StudentCourse#name, but this property is actually of Boolean type, so comparing it to String doe snot make much sense. You have also doubled .id which is incorrect.
Next thing, I am not sure what this snipped should do, was the intention to link a student with given course? If so, you would probably like to add a list of students to a course, or a list of courses to a student (which sounds more correct).
Finally, when it comes to filtering a list, you can get students with first name Bob in this way:
var studentListContainsFirstNameBob: List<Student> = students
.filter { it.firstName.equals("Bob") }
.toList()
Mind the it variable refers to the element from the list, it could also be written:
var studentListContainsFirstNameBob: List<Student> = students
.filter { student -> student.firstName.equals("Bob") }
.toList()

Related

Dart compare unordered Lists with Objects

I have following problem. There are two Lists with Articles in it. In the following example the result prints me false. But the Articles are the same. I think thats, because these are different objects, if I add in both lists article1, it will be true.
I also tried DeepCollectionEquality.unordered().equals from this issue:
How can I compare Lists for equality in Dart?
But it is also giving me FALSE back.
In my real project, I have two Lists with Articles in it. These lists are not sorted, so one Article can be the first in one list, and an article with the same id and name can be the last one in the other list. But if both lists have the same articles (with the same name and id) it should result with true.
var a = List<Article>();
var b = List<Article>();
var article1 = Article(id: "1", name: "Beer");
var article2 = Article(id: "1", name: "Beer");
a.add(article1);
b.add(article2);
print(listEquals(a, b));
As you said , those are different objects, you need to override the equal operator of your class, like this:
class Article {
final String name;
final String id;
const Article({this.id,this.name});
#override
bool operator ==(Object other) =>
identical(this, other) ||
other is Article &&
runtimeType == other.runtimeType &&
id == other.id;
#override
int get hashCode => id.hashCode;
}
Then the result will be true, because the ids are the same.
Also you can take a look at this package
https://pub.dev/packages/equatable
As my solution I used the "equatable"- package: https://pub.dev/packages/equatable
For checking an unordered List, I use DeepCollectionEquality.unordered().equals instead of listEquals
var a = List<Article>();
var b = List<Article>();
var article1 = Article(id: "1", name: "Beer");
var article2 = Article(id: "2", name: "Tequilla");
var article3 = Article(id: "3", name: "VodkaBull");
var article4 = Article(id: "1", name: "Beer");
var article5 = Article(id: "2", name: "Tequilla");
var article6 = Article(id: "3", name: "VodkaBull");
a.add(article1);
a.add(article2);
a.add(article3);
b.add(article4);
b.add(article5);
b.add(article6);
print(listEquals(a, b));
print(DeepCollectionEquality.unordered().equals(a, b));
The Code for my Article looks as following:
import 'package:equatable/equatable.dart';
class Article extends Equatable {
String id;
String name;
Article({this.id, this.name});
#override
// TODO: implement props
List<Object> get props => [id, name];
}

Retrieving data from Firebase (Realtime Database) into a list (Kotlin)

The RealtimeDatabase structure in Firebase
I want to go over the entire users in "mifkada" and to add them into a list as a BlogPost object:
class BlogPost (
var namerv: String,
var gafrv: String,
var placerv: String,
var phonerv: String,
var notesrv: String
) {
constructor() : this("", "", "", "", "") {}
}
I tried to do it with a for loop but it doesn't work the way I wrote it
class DataSource{
companion object{
fun createDataSet(): ArrayList<BlogPost>{
var databaseMifkada = FirebaseDatabase.getInstance().getReference("mifkada")
val list = ArrayList<BlogPost>()
val postListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if(dataSnapshot!!.exists()){
list.clear()
for (e in dataSnapshot.children){
val post = e.getValue(BlogPost::class.java)
list.add(post!!)
}
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
}
}
databaseMifkada.addValueEventListener(postListener)
return list
}
}
}
The values of your constructor does not match the names of your database values
class BlogPost (
var namerv: String,
var gafrv: String,
var placerv: String,
var phonerv: String,
var notesrv: String
) {
constructor() : this("", "", "", "", "") {}
}
Should be
class BlogPost (
var name: String,
var gaf: String,
var place: String,
var phone: String,
var notes: String
) {
constructor() : this("", "", "", "", "") {}
}
You need to have the same name because when you do
val post = e.getValue(BlogPost::class.java)
it will look for those field names under the reference, and if it can't be reached, you can't get those values

How to add dynamic values to field injections list with custom trigger to camunda properties panel?

I have two questions here
Is it possible to add dynamic lists values to field injection list input ?
Can I create a trigger for this so this can be initiated from any other input selection say a class selection will populate all fields
I was just looking into FieldInjection.js whether that can be extented for the same
Can someone please provide a hint or direction for this ?
Thanks.
For anyone interested in the answer, I was able to achieve the above goal by changing the set function of the Java Class select input as folllowing
few imports
var extensionElementsHelper = require('../../../../helper/ExtensionElementsHelper'),
elementHelper = require('../../../../helper/ElementHelper')
var CAMUNDA_FIELD_EXTENSION_ELEMENT = 'camunda:Field';
function getExtensionFields(bo) {
return bo && extensionElementsHelper.getExtensionElements(bo, CAMUNDA_FIELD_EXTENSION_ELEMENT) || [];
}
then changing the set function to create extension element and push the field values as :
set: function(element, values, node) {
var bo = getBusinessObject(element);
var type = getImplementationType(element);
var attr = getAttribute(type);
var prop = {}
var commands = [];
prop[attr] = values.delegate || '';
var extensionElements = getExtensionFields(bo);
//remove any extension elements existing before
extensionElements.forEach(function(ele){
commands.push(extensionElementsHelper.removeEntry(getBusinessObject(element), element, ele));
});
if(prop[attr] !== ""){
var extensionElements = elementHelper.createElement('bpmn:ExtensionElements', { values: [] }, bo, bpmnFactory);
commands.push(cmdHelper.updateBusinessObject(element, bo, { extensionElements: extensionElements }));
var arrProperties = ["private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varOne","private org.camunda.bpm.engine.delegate.Expression com.cfe.extensions.SampleJavaDelegate.varTwo"]
var newFieldElem = "";
arrProperties.forEach(function(prop){
var eachProp = {
name:"",
string:"",
expression:""
}
var type = prop.split(" ")[1].split(".").reverse()[0];
var val = prop.split(" ")[2].split(".").reverse()[0];
eachProp.name = val;
if( type == "String"){
eachProp.string = "${" + val +" }"
}else if( type == "Expression"){
eachProp.expression = "${" + val +" }"
}
newFieldElem = elementHelper.createElement(CAMUNDA_FIELD_EXTENSION_ELEMENT, eachProp, extensionElements, bpmnFactory);
commands.push(cmdHelper.addElementsTolist(element, extensionElements, 'values', [ newFieldElem ]));
});
}
commands.push(cmdHelper.updateBusinessObject(element, bo, prop));
return commands;
}
Cheers !.

How to get two data from FMDB and return a String combined two of them in swift?

I have two records in my database, 'FirstName and LastName and I wanna get two of them then return a FullName, showing FullNames in tableView. Using Swift3 and Xcode8.2.1, FMDB
here's the func of getFullName
func getFullName() -> String{
StudentDataBase.getInstance()
sharedInstance.database!.open()
let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT FirstName, LastName FROM Student_info", withArgumentsIn: nil)
let fullName = (result?.string(forColumn: "FirstName"))! + " " + (result?.string(forColumn: "LastName"))!
return fullName
}
sharedInstance is a global one, StudentDataBase is s singleton class:
class StudentDataBase : NSObject {
var database: FMDatabase? = nil
var pathToDB: String!
class func getInstance() -> StudentDataBase{
if((sharedInstance.database) == nil)
{
sharedInstance.database = FMDatabase(path: Utility.getPath("data.db"))
}
return sharedInstance
}
and my Student.swift goes like this:
import UIKit
//the model class to fetch the data from data.db
class Student : NSObject {
var studentID: String = String()
var fstName: String = String()
var lstName: String = String()
var phoneNum: String = String()
}
I got a thread goes like this enter image description here
Thank you so much if anyone can help
After editing the Query into
let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT ifnull(FirstName,'') as FirstName, ifnull(LastName,'') as LastName FROM Student_info", withArgumentsIn: nil)
There's another error in combining them into one String:
enter image description here
You are getting this crash because either you are getting nil for FirstName or LastName, and you can use ifnull with your select query and return empty string if it is nil. So change your query like this way.
let result : FMResultSet! = sharedInstance.database!.executeQuery("SELECT ifnull(FirstName,'') as FirstName, ifnull(LastName,'') as LastName FROM Student_info", withArgumentsIn: nil)
Note: You haven't added WHERE clause with query so that this will give you all the records form Student_info table also it is batter if you check result.next() to confirm result contains records or not.

How to convert a dynamic list into list<Class>?

I'm trying to convert a dynamic list into a list of class-model(Products). This is how my method looks like:
public List<Products> ConvertToProducts(List<dynamic> data)
{
var sendModel = new List<Products>();
//Mapping List<dynamic> to List<Products>
sendModel = data.Select(x =>
new Products
{
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data, null).ToString()
}).ToList();
}
I have tried these both ways to get the property values, but it gives me null errors saying these properties doesn't exist or they are null.
Name = data.GetType().GetProperty("Name").ToString(),
Price = data.GetType().GetProperty("Price").GetValue(data,
null).ToString()
This is how my Model-class looks like:
public class Products
{
public string ID { get; set; }
public string Name { get; set; }
public string Price { get; set; }
}
Can someone please let me know what I'm missing? thanks in advance.
You're currently trying to get properties from data, which is your list - and you're ignoring x, which is the item in the list. I suspect you want:
var sendModel = data
.Select(x => new Products { Name = x.Name, Price = x.Price })
.ToList();
You may want to call ToString() on the results of the properties, but it's not clear what's in the original data.