Lambda expression java 8 map method returns values - dictionary

I am practicing complex Lambda expressions on my own ,for this example , I want to use return item in Map , how to use Map lambda expression to process list of students name who got zero marks in language.
public class Student {
private String name;
private Integer age;
private List<Marks> individualMarks;
}
public class Marks {
private Integer maths;
private Integer science;
private Integer language;
private Integer sports;
}
List studentNames = Student.stream().map(student ->
student.getIndividualMarks().stream().map(marks -> ((marks.getSport == null )
return marks
})..collect(Collectors.toList());
List studentNames = Student.stream().map(student ->
student.getIndividualMarks().stream().map(marks -> ((marks.getSport == null )
return marks
})..collect(Collectors.toList());

Related

JavaFX - ListProperty conditional binding

in my code i have a tableview bound to a ListProperty.
I am able to retrieve all the data correctly but i need to apply a condition to this data set based on a specific property of each object in it.
Is it possible?
This is the model:
public class Ticket {
private String number;
private String sys_id;
private String short_description;
private String description;
private String opened_by;
private String assigned_to; // tabella esterna
private String assignment_group; // tabella esterna
private int incident_state; // 2: assigned - 3: wip - 4: hold
private String sys_created_on;
private Date sys_updated_on;
private int priority; // 1: critical
private boolean isVisible; // per nasconderlo nella tabella riassuntiva
private boolean isAlarmed; // per silenziare le notifiche
In the controller i have bound the tableview to a ListProperty (returned by ticketService.ticketsProperty()):
serviceNowTicket_tableView.itemsProperty().bindBidirectional(ticketService.ticketsProperty());
I just need to filter this by the ticket "isVisible" property.
Maybe via BooleanBinding?

DynamoDBMapper - DynamoDBDocument and local secondary indexes

I am using DynamoDB SDK 1.11.185 version. I have a Client entity mapped to Clients DynamoDB table through DynamoDBMapper annotations. One of the attributes contains nested values (see code examples below). I want to add a local secondary index to zone attribute from Options class. Once I want to save an object, I got a null pointer exception from this class
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperTableModel
line 415. Looks like a bug from the libraries.
P.D. If I generate the index over clientId attribute from Client entity, everything work fine.
#DynamoDBTable(tableName="Clients")
public class Client {
private String id;
private String clientId;
private Date created;
private Options options;
public Client() {
}
public Client(String id, String clientId, Options options) {
this.id = id;
this.clientId = clientId;
this.options = options;
this.created = new Date();
}
#DynamoDBHashKey
public String getId() { return id; }
public void setId(String id) { this.id = id; }
#DynamoDBAttribute
public String getClientId() { return clientId; }
public void setClientId(String clientId) { this.clientId = clientId; }
#DynamoDBAttribute
public Options getOptions() { return options; }
public void setOptions(Options options) { this.options = options; }
#DynamoDBRangeKey
public Date getCreated() { return created; }
public void setCreated(Date created) { this.created = created; }
}
#DynamoDBDocument
public class Options {
private String zone;
public Options() {
}
public Options(String zone) {
this.zone = zone;
}
#DynamoDBIndexRangeKey(localSecondaryIndexName = "zone-index")
public String getZone() { return zone; }
public void setZone(String zone) { this.zone = zone; }
}
**************************** EDITED *************************
Correct answer by #Raniz and
Indexing on nested field
It can be done using JSON attributes though:
DynamoDB create index on map or list type
You can't use nested attributes in the key schema for an index.
I assume you've created the index with options.zone in the schema which means that DynamoDB is expecting a top-level attribute with that exact name - i.e. an attribute named options.zone and not an attribute named zone nested under the options attribute.
Excerpt from here:
The key schema for the index. Every attribute in the index key schema
must be a top-level attribute of type String, Number, or Binary. Other
data types, including documents and sets, are not allowed. Other requirements for the key schema depend on the type of index:
For a global secondary index, the partition key can be any scalar attribute of the base table. A sort key is optional, and it too can be
any scalar attribute of the base table.
For a local secondary index, the partition key must be the same as the base table's partition key, and the sort key must be a non-key
base table attribute.
To use zone in your index schema you'll need to either move or duplicate it so it's available on the top level. The easiest way of accomplishing this would probably be to add a getter to Client that returns options.zone:
#DynamoDBIndexRangeKey(localSecondaryIndexName = "zone-index")
public String getZone() {
if (options != null) {
return options.getZone();
}
return null;
}

DynamoDb - Filter or Scan based on attributes in Collection of DynamoDBDocument

I would like to know if it is possible to filter / scan based on attributes in a collection of DynamoDBDocuments. Lets say I have this:
#DynamoDBTable(tableName = "Orders")
public class Order {
#DynamoDBHashKey
#DynamoDBAutoGeneratedKey
private String id;
#DynamoDBAttribute
#DynamoDBTypeConverted(converter = LocalDateTimeConverter.class)
private LocalDateTime orderDate;
#DynamoDBAttribute
private Address shipTo;
#DynamoDBAttribute
private Address billTo;
#DynamoDBAttribute
private List<OrderItem> items;
}
#DynamoDBDocument
public class Address {
private String name;
private String street;
private String city;
private String state;
private String zip;
}
#DynamoDBDocument
public class OrderItem {
private String product;
private int qty;
private double itemCost;
}
Lets assume I want to find all orders which have one or more items where the product is "widgets". I believe the answer is no. With a relational DB I would do:
SELECT o FROM Orders o, OrderItems i WHERE o.id = i.id AND i.product="widgets"
Would a better practice be to put the order items in their own table and have a orderId attribute in it and then query order items based on the product and then grab the order based on the order ID?
If you use a map instead of a list for #DynamoDBAttribute items, where the key of the map is the product, then you can use a filter expression attribute_exists(items.widgets) to down-select.

What is the best method for attaching a single key/value pair attribute to an enumeration?

I'm trying to figure out what the best method is for attaching a single key/value pair attribute to an enumeration where the key is my MerchantId and the value is the corresponding TransactionKey.
What I currently do is put a comma delimited string into a StringValueAttribute class:
Public Enum Merchants
<StringValue("coke,faj80785hq+faf=-1=-jfa+">
Coke = 0
<StringValue("pepsi,adfji=-901jnas++fdj98ua")>
Pepsi = 1
<StringValue("drpepper,jk878-=+9kdkdja0=a=f--daj")>
DrPepper = 2
End Enum
Public Property Merchant As Merchants
I pull out the key or MerchantId by calling .GetStringValue().Split(","c)(0):
Public ReadOnly Property MerchantId() As String
Get
Return Merchant.GetStringValue().Split(","c)(0)
End Get
End Property
I pull out the value or TransactionKey by calling .GetStringValue().Split(","c)(1):
Public ReadOnly Property TransactionKey() As String
Get
Return Merchant.GetStringValue().Split(","c)(1)
End Get
End Property
Is this the most efficient way to do this? Instead of StringValueAttribute, what about creating an attribute using a Dictionary(Of String, String) since it is a key/value pair list? Or String Array or List? Maybe something in LINQ? Or is it simply already efficient as it can be?
You can use the following custom attribute and extension methods to get the values. Some things to note:
It's in C#, hope that's ok :)
The extension methods class caches the MerchantIds and TransactionIds in static scope, so should be pretty efficient.
You get the MerchantId by calling (e.g.) Merchants.Coke.GetMerchantId();.
You get the TransactionId by calling (e.g.) Merchants.Coke.GetTransactionId();.
Also, the extension methods don't bother checking that the Merchants value passed to them is valid, so you could break it by calling ((Merchants)76282).GetMerchantId().
[AttributeUsage(AttributeTargets.Field)]
public class MerchantDataAttribute : Attribute
{
public MerchantDataAttribute(string merchantId, string transactionId)
{
this.MerchantId = merchantId;
this.TransactionId = transactionId;
}
public string MerchantId
{
get;
private set;
}
public string TransactionId
{
get;
private set;
}
}
public static class MerchantsExtensions
{
private static readonly Dictionary<Merchants, MerchantDataAttribute>
_merchantsCache = CacheMerchantsCache();
public static string GetMerchantId(this Merchants merchants)
{
return _merchantsCache[merchants].MerchantId;
}
public static string GetTransactionId(this Merchants merchants)
{
return _merchantsCache[merchants].TransactionId;
}
private static Dictionary<Merchants, MerchantDataAttribute> CacheMerchantsCache()
{
return Enum.GetValues(typeof(Merchants))
.Cast<Merchants>()
.Select(m => new
{
Merchant = m,
MerchantAttribute = GetMerchantAttribute(m)
})
.ToDictionary(m => m.Merchant, m => m.MerchantAttribute);
}
private static MerchantDataAttribute GetMerchantAttribute(Merchants merchant)
{
return typeof(Merchants)
.GetMember(merchant.ToString())
.First()
.GetCustomAttributes(typeof(MerchantDataAttribute), inherit: false)
.Cast<MerchantDataAttribute>()
.First();
}
}
I would suggest creating your own attribute class which takes both values in a type-safe manner and names them appropriately. Or, if not every item will have both values, create two separate attributes, one for each value.
Or better yet, don't use an Enum at all. Create your own class that takes all three values in the constructor and then create a class with shared properties for each item, as such:
Public Class Merchants
Public Shared ReadOnly Property Coke() As Merchant
Get
Return _coke
End Get
End Property
Private Shared _coke = New Merchant(0, "Coke", "faj80785hq+faf=-1=-jfa+")
...
End Class
For any future visitors, I thought I'd post the VB version of the answer, since that's what I tagged the question with. Also, I had to do things slightly different due to VB requiring extensions to be inside of a Module.
Here is the Module:
(I used a lot of line continuation for easier readability. Also, for the sake of readability in this example I imported SomeClass so that I didn't have to type out that NameSpace)
Imports SomeClass
Module MerchantsExtensions
Private ReadOnly MerchantsCache _
As Dictionary(Of Merchants, MerchantDataAttribute) _
= CacheMerchantsCache()
Private Function CacheMerchantsCache() _
As Dictionary(Of Merchants, MerchantDataAttribute)
Return [Enum].GetValues(GetType(Merchants)) _
.Cast(Of Merchants)() _
.Select(Function(m) New With
{
.Merchant = m,
.MerchantAttribute = GetMerchantAttribute(m)
}) _
.ToDictionary(Function(m) m.Merchant, _
Function(m) m.MerchantAttribute)
End Function
Private Function GetMerchantAttribute(merchant As Merchants) _
As MerchantDataAttribute
Return GetType(Merchants) _
.GetMember(merchant.ToString()) _
.First() _
.GetCustomAttributes(GetType(MerchantDataAttribute), _
inherit:=False) _
.Cast(Of MerchantDataAttribute)() _
.First()
End Function
<Runtime.CompilerServices.Extension()>
Public Function GetMerchantId(merchants As Merchants) As String
Return MerchantsCache(merchants).Id
End Function
<Runtime.CompilerServices.Extension()>
Public Function GetTransactionKey(merchants As Merchants) As String
Return MerchantsCache(merchants).TransactionKey
End Function
End Module
Here is the implementation of the extension methods in a class I named SomeClass for this example:
Public Class SomeClass
Public Enum Merchants
<MerchantData("coke", "faj80785hq+faf=-1=-jfa+")>
Coke = 0
<MerchantData("pepsi","adfji=-901jnas++fdj98ua")>
Pepsi = 1
<MerchantData("drpepper","jk878-=+9kdkdja0=a=f--daj")>
DrPepper = 2
End Enum
<AttributeUsage(AttributeTargets.Field)>
Public Class MerchantDataAttribute : Inherits Attribute
Public Sub New(merchantId As String, transactionKey As String)
_Id = merchantId
_TransactionKey = transactionKey
End Sub
Public Property Id() As String
Public Property TransactionKey() As String
End Class
End Class

List of select data in Entity Framework (linq)?

This is my function:
Public Function GetAllEmployee() As List(Of Employees)
Return DB.Employees.Select(Function(q) New With {q.EmployeeID, q.LastName,q.FirstName}).ToList()
End Function
I'm getting an error:
Value of type System.Collections.Generic.List(Of <anonymous type>) cannot be converted to System.Collections.Generic.List(Of NorthwindModel.Employees).
You're instantiating an Anonymous object inside your select statement. Try using this:
Return DB.Employees.ToList()
EDIT: If you want to give back a list of objects with only those 3 properties, you can define a class containing those properties:
Public Class MyEmployees
Public Property EmployeeId As Long
Public Property FirstName As String
Public Property LastName As String
End Class
Then return a list of that new class:
Public Function GetAllEmployee() As List(Of MyEmployees)
Return DB.Employees.Select(Function(q) New MyEmployees With { .EmployeeId = q.EmployeeID, .LastName = q.LastName, .FirstName = q.FirstName}).ToList()
End Function

Resources