get max value in java8 list using stream [duplicate] - list

This question already has answers here:
Java Stream: find an element with a min/max value of an attribute
(9 answers)
Closed 5 years ago.
I want to find max value in java list using java8 lambda expression,
so, I have a Class called TicketMaster and item table is TicketMasterLog ,in TicketMasterLog class I have StatusMaster Class statusId reference column, so here i want to find max statusId in TicketMasterLog List, below i'll give my code please refer
#Entity
#Table(name="ticket_master")
#NamedQuery(name="TicketMaster.findAll", query="SELECT t FROM TicketMastert")
public class TicketMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="TICKET_ID", unique=true, nullable=false, length=10)
private String ticketId;
//bi-directional many-to-one association to TicketMasterLog
#OneToMany(mappedBy="ticketMaster",cascade=CascadeType.ALL)
private List<TicketMasterLog> ticketMasterLogs;
//getters and stters
}
and TicketMasterItem Table is
#Entity
#Table(name="ticket_master_log")
#NamedQuery(name="TicketMasterLog.findAll", query="SELECT t FROM TicketMasterLog t")
public class TicketMasterLog implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private TicketMasterLogPK id;
//bi-directional many-to-one association to StatusMaster
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="STATUS_ID")
private StatusMaster statusMaster;
//bi-directional many-to-one association to TicketMaster
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="TICKET_ID", nullable=false, insertable=false, updatable=false)
private TicketMaster ticketMaster;
//getters and setters
}
and StatusMaster Table is
#Entity
#Table(name="status_master")
#NamedQuery(name="StatusMaster.findAll", query="SELECT s FROM StatusMaster s")
public class StatusMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="STATUS_ID", unique=true, nullable=false, length=10)
private String statusId;
#Column(name="STATUS_NAME", length=45)
private String statusName;
//bi-directional many-to-one association to TicketMasterLog
#OneToMany(mappedBy="statusMaster")
private List<TicketMasterLog> ticketMasterLogs;
//getters and setters...
Now I have a TicketMasterlog List
List<TicketMasterLog> tl = //some objects;
so in that list I want find max status id value
thanking you.

You can use:
Stream<TicketMasterLog> ticketMasterLogStream = tl.stream();
TicketMasterLog max = ticketMasterLogStream.reduce((a,b)->
a.getStatusId.compareTo(b.getStatusId) > 0 ? a:b;
).get()

Related

Getting Relationship properties using spring data neo4j node repository

If we have a Company Node like this which is linked to another Node (Location) using OWNS relationship.
#NodeEntity ("Company")
public class Company {
#Id
#Property
private String companyId;
#Property
private String partyId;
#Relationship (type = "OWNS", direction = Relationship . OUTGOING )
private Set<Location> ownedLocations;
}
OWNS relationship
#RelationshipEntity (type = "OWNS")
public class Owns {
#Property
private String ownsProperty;
#StartNode
private Company company;
#EndNode
private Location location;
}
Here is the Repository
#Repository
public interface CompanyRepository extends Neo4jRepository<Company, String> {
#Query ("match (c:Company)-[x:OWNS]-(y) where c.partyId = $0 return c,x,y")
Stream<Company> getCompaniesWithRelationsByPartyId(final String partyId);
}
So when i run this query i am getting only Company and Location entities but no OWNS ownsProperty. How to get relationship properties using above repository?
NOTE: I don't want to use #QueryResult
enter code here
You have to define the Owns relationship entity as the type for the relationship in the Company like this
#Relationship (type = "OWNS", direction = Relationship . OUTGOING )
private Set<Owns> ownedLocations;

Is DynamoDB sorting impossible?

I connected DynamoDB with Spring-boot.
Normal findAll() is work.
Pageable is work too.
But when I insert sort value, it's not a work.
And I tried to use findAllByOrderByBn() method.
This is my table information.
Partition key(hash key) is id.
Sort key(range key) is bn.
How can I sort?
#Data
#DynamoDBTable(tableName = "tableName")
public class EntityName implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#DynamoDBHashKey
#DynamoDBAutoGeneratedKey
private String id;
#DynamoDBAttribute private String bn;
#DynamoDBAttribute private String fr; // from
#DynamoDBAttribute private String to; // to
}
#EnableScan
#EnableScanCount
//public interface RepositoryName extends CrudRepository<EntityName, String> {
public interface EthereumTransactionRepository extends PagingAndSortingRepository<EntityName, String> {
/* Find */
Page<EntityName> findAll(Pageable pageable);
Page<EntityName> findByFrAndToBeforeOrderByBnDesc(String fr, String to, Pageable pageable);
}
If you need more code, reply me.
Firstly, if you are trying to sort based on range key, set the sort key. Annotation for the sort key is #DynamoDBRangeKey. So change the class to below
public class EntityName implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#DynamoDBHashKey
#DynamoDBAutoGeneratedKey
private String id;
#DynamoDBRangeKey private String bn;
#DynamoDBAttribute private String fr; // from
#DynamoDBAttribute private String to; // to
And also if you want to sort in ascending or descending, you can refer to following documentation : https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/dynamodbv2/datamodeling/DynamoDBQueryExpression.html#withScanIndexForward-boolean-

Designing Model with foreign key

I am building an ORM by using Unit or Work and Repository using Dapper. I have searched the internet on this problem and no luck.
I have the following tables:
As you can see, Instance has Entity inside. I have 2 approaches:
Approach 1:
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public Entity Entity {get;set;}
public string Name {get;set;}
}
How can I get value for Entity with this approach?
Approach 2 (according to this link):
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public int EntityId {get;set;}
public string Name {get;set;}
}
Which design is better for use?
You can use QueryMultiple if you want to fetch the data from two different tables and fill it up in two different POCO classes. Following is copied from here:
string sql = "SELECT * FROM Invoice WHERE InvoiceID = #InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = #InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
{
var invoice = multi.Read<Invoice>().First();
var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
}
Both the models you mentioned in your code can be handled with this approach.
As an alternative approach, you can combine your two POCOs in one or you can use inheritance as well. But, looking at your data model, I do not think this is applicable to this particular case.
Which design is better for use?
Up to you. Whatever suits your project needs keeping down the unnecessary complexities is good for you.

JPA OneToOne bi-directional

I have two entities and they are related to each other through a one to one relationship. User is the owner of Balance. I set Hibernate to automatically create tables and this does not seem to be working. The problem may be caused by other causes but I'd like to make sure that I have the one to one relationship configured correctly first.
Can you please check the following entities and tell me if they are correct?
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne
#JoinColumn(name = "balance_id", referencedColumnName = "id")
private Balance balance;
}
#Entity
#Table(name = "balances")
public class Balance implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#OneToOne(mappedBy = "users")
private User user;
}
No, it's not correct. The value of mappedBy must be the name of the attribute, in the other entity, which is the owner side of the association:
#OneToOne(mappedBy = "balance")

Mapping Extra Attribute in a Join Table JPA 2

I am trying to model this relationship following this link http://www.javaworld.com/javaworld/jw-01-2008/images/datamodel.gif
Its the usual Many to Many relationship between Order and Products but I dont know how to add the extra columns in the Join table.
#Entity
#Table(name = "Orders")
public class Order {
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "ORDER_LINES", joinColumns = { #JoinColumn(name = "ORDER_ID") }, inverseJoinColumns = { #JoinColumn(name = "PROD_ID") })
private Set<Product> products;
}
#Entity
#Table(name="PRODUCTS")
public class Product {
#ManyToMany(mappedBy="products")
private Set<Order> orders;
}
How to add Join Table extra attribute in JPA 2.0?
Thanks
There is no concept of having additional persistent attribute in relation in JPA (2.0). That's why relation with property is actually intermediate entity.
From both Order and Product entities, you need one-to-many relationship to new entity. Because of bidirectional relationship, new entity will have many-to-one relationships to Order and Product.
You need to go for something like this (shows only relationships, id's and other mappings stripped away):
#Entity
#Table(name="order_item")
public class OrderItem {
#ManyToOne
private Order order;
#ManyToOne
private Product product;
}
#Entity
public class Order {
#OneToMany (mappedBy = "order")
private Set<OrderItem> orderItems;
}
#Entity
public class Product {
#OneToMany(mappedBy = "product")
private Set<OrderItem> orderItems;
}