Java custom classes - java

import java.util.ArrayList;
public class Watch{
// instance variables for the class watch
private String name;
private long serial_no;
private String desc;
private String color;
private double price;
private double weight;
private int hour;
private int min;
private int sec;
ArrayList<Watch> watchStore = new ArrayList<Watch>();
public void addWatch(String nme, long s_r, String ds, String cl, double pr, double wg){
watchStore.add(new Watch(nme, s_r, ds, cl, pr, wg));
}
public String disWatch(){
return watchStore.get(watchStore) + "";
}
In my addWatch method I am creating a new Watch to add to an ArrayList, inside of the Watch class. Is this possible?

I guess it would be better to have two classes: Store and Watch, where the class Store contains a list like ArrayList<Watch> watches;.
Class Store:
public class Store {
private ArrayList<Watch> watches;
public Store() {
watches = new ArrayList<>();
// Add first watch
watches.add(new Watch(...));
}
}
And the class Watch:
public class Watch {
private String name;
private long serial_no;
private String desc;
private String color;
private double price;
private double weight;
private int hour;
private int min;
private int sec;
public Watch(...) {
// ...
}
}

Yes, why not? But make more a container class to store watches (WatchStore).

Related

how can i create a summary using collectors

public class Call {
private String status;
private String callName;
private int duration;
private int waitedTime;
}
I have a list of calls and i have to create a summary, like this:
public class CallSummary {
private String callName;
private List<ItemSummary> items;
private int averageDuration;
private int averageWaitedTime
}
public class itemSummary {
private String status;
private Integer percentage;
}
My goal is show a summary like :
{
callname:"sac",
averageDuration:"60",
averageWaitedTime:"10",
items:{
status:"failed",
percentage:"40"
status:"answered","60"
}
}
how can i do it using java 8 stream and Collectors ?

Read data from a text file and create and object but text have different object information

I need some help: I'm making a Internship Management Program on Java, but I've got one problem, I have a text file (input.txt) where I have all the student and instructors information on it for example:
Department,CME,Computer Engineering,Assoc.Prof.Dr.,Mehmet Hilal OZCANHAN,Res.Asst.,Elife KIYAK,Res.Asst.,Goksu TUYSUZOGLU,Hardware Training,2,Software Training,4,Free,6
Department,CEV,Environmental Engineering,Prof.Dr.,Ayse GUR,Res.Asst.,Sibel TOSUN,Res.Asst.,Ahmet TARAK,Practical Training,3,Theoretical Training,2,Free,5
I have categorize them using the Student class and after that I have to list all classes.
public class Date {
private int day;
private int month;
private int year;
}
public class Phone {
private int phone_country_code;
private int phone_area_code;
private int phone_number;
public Phone(int phone_country_code, int phone_area_code, int phone_number) {
super();
this.phone_country_code = phone_country_code;
this.phone_area_code = phone_area_code;
this.phone_number = phone_number;
}
}
public class Student {
private int student_number;
private String student_name;
private String gender;
private Phone student_phone;
private Date student_birthdate;
public Student(int student_number, String student_name, String gender, Phone student_phone,
Date student_birthdate) {
super();
this.student_number = student_number;
this.student_name = student_name;
this.gender = gender;
this.student_phone = student_phone;
this.student_birthdate = student_birthdate;
}
}

Java Stream -> Creating a list from another list of different structure

I am new to Java Stream api and your help is highly appreciated.
I am trying to convert this structure(first Structure) to
[(id=BNA, name=Nashville, TN, loadsCount=1, distance=null, metricScoresList=[BattingOrderResponse.MetricScoresList(identifier=BNA, name=null, aggregatedScore=35.5, onTimeToDestinationPercentage=0.0, onTimeToPickupPercentage=0.0, onTimeToPickupDepartPercentage=0.0, tenderAcceptancePercentage=18.2, tenderCancellationPercentage=0.0, appUsageCompliancePercentage=100.0, revenue=0.0, loadsCount=1, distance=0.0)])...]
This is the class model:
#ToString
#Getter
public final class BattingOrderResponse {
private final String id;
private final String name;
private final long loadsCount;
private final Distance distance;
private final List<MetricScores> metricScores;
#JsonCreator
public BattingOrderResponse(#JsonProperty("id") final String id,
#JsonProperty("name") final String name,
#JsonProperty("loadsCount") final long loadsCount,
#JsonProperty("distance") final Distance distance,
#JsonProperty("metricScores") final List<MetricScores> metricScores) {
this.id = id;
this.name = name;
this.loadsCount = loadsCount;
this.distance = distance;
this.metricScores = metricScores;
}
#ToString
#Getter
public static final class Distance {
private final double value;
private final String unit;
#JsonCreator
public Distance(#JsonProperty("value") final double value,
#JsonProperty("unit") final String unit) {
this.value = value;
this.unit = unit;
}
}
#ToString
#Getter
public static final class MetricScores {
private final String identifier;
private final String name;
private final double aggregatedScore;
private final double onTimeToDestinationPercentage;
private final double onTimeToPickupPercentage;
private final double onTimeToPickupDepartPercentage;
private final double tenderAcceptancePercentage;
private final double tenderCancellationPercentage;
private final double appUsageCompliancePercentage;
private final double revenue;
private final long loadsCount;
private final double distance;
#JsonCreator
//CHECKSTYLE:SUPPRESS:ParameterNumberCheck
public MetricScores(#JsonProperty("identifier") final String identifier,
#JsonProperty("name") final String name,
#JsonProperty("aggregatedScore") final double aggregatedScore,
#JsonProperty("onTimeToDestinationPercentage") final double onTimeToDestinationPercentage,
#JsonProperty("onTimeToPickupPercentage") final double onTimeToPickupPercentage,
#JsonProperty("onTimeToPickupDepartPercentage") final double onTimeToPickupDepartPercentage,
#JsonProperty("tenderAcceptancePercentage") final double tenderAcceptancePercentage,
#JsonProperty("tenderCancellationPercentage") final double tenderCancellationPercentage,
#JsonProperty("appUsageCompliancePercentage") final double appUsageCompliancePercentage,
#JsonProperty("revenue") final double revenue,
#JsonProperty("loadsCount") final long loadsCount,
#JsonProperty("distance") final double distance) {
this.identifier = identifier;
this.name = name;
this.aggregatedScore = aggregatedScore;
this.onTimeToDestinationPercentage = onTimeToDestinationPercentage;
this.onTimeToPickupPercentage = onTimeToPickupPercentage;
this.onTimeToPickupDepartPercentage = onTimeToPickupDepartPercentage;
this.tenderAcceptancePercentage = tenderAcceptancePercentage;
this.tenderCancellationPercentage = tenderCancellationPercentage;
this.appUsageCompliancePercentage = appUsageCompliancePercentage;
this.revenue = revenue;
this.loadsCount = loadsCount;
this.distance = distance;
}
}
}
to
[(id=BNA, name=null, overallScore=35.5, onTimeScore=0.0, TenderAcceptanceScore=18.2, appUsageScore=100.0),...]
class model:
#Getter
#ToString
#Builder
public final class DomicileScore {
private final String id;
private final String name;
private final double overallScore;
private final double onTimeScore;
private final double TenderAcceptanceScore;
private final double appUsageScore;
}
Hint: id is BattingOrderResponse.id
name is BattingOrderResponse.name
overallScore is BattinOrderResponse.MetricScore
and remaining all are from BattinOrderResponse.MetricScore
where it should be 'name=Nashville' instead of 'name=null' (which has been referred from metricScoresList.
This is the code that i have tried.
scoreByDomicile.stream()
.peek(i -> System.out.println(i.getName()))
.map(i -> i.getMetricScoresList().get(0))
.map(i -> DomicileScore.builder()
.id(i.getIdentifier())
.name(i.getName())
.overallScore(i.getAggregatedScore())
.appUsageScore(i.getAppUsageCompliancePercentage())
.onTimeScore(i.getOnTimeToDestinationPercentage())
.TenderAcceptanceScore(i.getTenderAcceptancePercentage())
.build())
.collect(Collectors.toList());
where scoreByDomicile is the list of the raw data as in my first structure. I need to add the outcome of peek in the map(second map in the code) inside the build().
I am struck with this for last few hours and not able to resolve it. Let me know if you need more details. Thanks in advance.
You need both references, so you cann't use the double mapping
Try with this:
scoreByDomicile.stream()
.peek(i -> System.out.println(i.getName()))
.map(obj -> {
MetricScores i = obj.getMetricScoresList().get(0); //
return DomicileScore.builder()
.id(i.getIdentifier())
.name(obj.getName()) // obj has the original name
.overallScore(i.getAggregatedScore())
.appUsageScore(i.getAppUsageCompliancePercentage())
.onTimeScore(i.getOnTimeToDestinationPercentage())
.TenderAcceptanceScore(i.getTenderAcceptancePercentage())
.build();
})
.collect(Collectors.toList());

Java How to get a value from different class

I got this code sample
public class Plane {
private String id;
private Flight flight;
private int seats;
public int getSeats() {
return seats;
}
}
public class Flight {
private String id;
private Set<Passenger> passengers;
private Set<Employee> crew;
private String destination;
private int flighTime; // minutes past Midnight
private int flightDuration; // in minutes
}
And now I'm trying to implement Flight's method, Add1Passenger, so I need to look up to Plane, if there is a free seat ( number of seats is less than number of Flight's passengers) but I don't know how to do such thing. Or is there any better solution ?
You should add a getter method to your Plane class that is public.
public class Plane {
private String id;
private Flight flight;
private int seats;
public int getSeats(){
return seats;
}
}
Edit
You can have the Plane be a property of the Flight and pass in in via the constructor. So now you have a Plane associated with the flight
public class Flight {
private String id;
private Set<Passenger> passengers;
private Set<Employee> crew;
private String destination;
private int flighTime; // minutes past Midnight
private int flightDuration; // in minutes
private Plane aircraft; // the aircraft assigned to the flight
public Flight(Plane airplane){
aircraft = airplane;
}
public Boolean addPassenger(Passenger passenger){
if(aircraft.getSeats() > passengers.size()){
passenges.add(passenger);
return true;
}
return false;
}
}
In theory you could go the other route of passing in the plane as an argument to addPassenger but one could make the argument that different instances of a plane could be passed in to the flight and vice versa if you pass in flight to the plane object, you can have different flights on a plane, which could be fine if that is a legit business requirement, but if the flight have different destinations that would not make sense.
here you are u can also make 3rd class where you store both classes, you have to ALWAYS Inicialize new object in constructor dont forget
public class Plane {
private String id;
private Flight flight;
private int seats;
Plane(Flight flight) {
this.flight = flight;
}
public void addPasagerToFlight() {
if (this.seats > flight.getPassagers()) {
flight.addPasagerToFlight();
}
}
}
public class Flight {
private String id;
private Set<Passenger> passengers;
private Set<Employee> crew;
private String destination;
private int flighTime; // minutes past Midnight
private int flightDuration; // in minutes
// for example use LinkedList ArrayList HashSet ....
public void addPasagerToFlight(Passenger pas) {
this.passengers.add(pas);
}
}

Can Orika map nested collections?

I would like to map a field with nested collection using Orika library. My field in class is defined as:
private final List<List<Pojo>> list = new LinkedList<List<Pojo>>();
Pojo is a simple POJO class. Unfortunately I've got a MappingException caused by NullPointerException in Orika's internal logic.
Did I do something in wrong way? Maybe I need to use Custom Mapping feature?
EDIT:
Here is my code:
public class Pojo {
private int field;
public int getField() {
return field;
}
public void setField(final int field) {
this.field = field;
}
}
public class Source {
private final List> list = new LinkedList>();
public List<List<Pojo>> getList() {
return list;
}
}
public class Destination {
private final List> listDest = new LinkedList>();
public List<List<Pojo>> getListDest() {
return listDest;
}
}
public class Main {
public static void main(final String[] args) {
final MapperFactory factory = new DefaultMapperFactory.Builder().build();
factory.classMap(Source.class, Destination.class).field("list", "listDest").byDefault().register();
final Source src = new Source();
final LinkedList<Pojo> nestedList = new LinkedList<Pojo>();
final Pojo pojo = new Pojo();
pojo.setField(8978);
nestedList.add(pojo);
src.getList().add(nestedList);
final MapperFacade facade = factory.getMapperFacade();
final Destination dest = facade.map(src, Destination.class);
System.out.println(dest.getListDest().get(0).get(0).getField());
}
}
Execution above code results this Exception:
Exception in thread "main" ma.glasnost.orika.MappingException: Error encountered while mapping for the following inputs:
rawSource=com.bbh.nested.Source#39185ce6
sourceClass=class com.bbh.nested.Source
destinationClass=class com.bbh.nested.Destination
You can see this Example:
public class ShopEntity {
private Long id;
private String name;
private String logo;
private String url;
private ProductCategory mainCategory;
private Set<ShopRel> shopRels = new HashSet<>(0);
private Account account;
// Assume getter/setter
}
public class ProductCategory extends BaseEntity {
private Long id;
private String name;
// Assume getter/setter
}
public class ShopRel {
private Long id;
private SaleChannel saleChannel;
private Boolean enabled;
// Assume getter/setter
}
public class SaleChannel {
private Long id;
private String name;
private String image;
private String description;
private Boolean active;
// Assume getter/setter
}
public class ShopDto {
private Long id;
private String name;
private String logo;
private String url;
private Long mainCategory;
private Set<ShopRelDto> shopRelDtos = new HashSet<ShopRelDto>();
// Assume getter/setter
}
public class ShopRelDto {
private Long channelId;
private String name;
private Boolean enabled;
// Assume getter/setter
}
public class MapperUtils {
private static final MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
private static final MapperFacade mapper = mapperFactory.getMapperFacade();
static {
mapperFactory.classMap(ShopEntity.class, ShopDto.class)
.field("mainCategory.id", "mainCategory")
.fieldMap("shopRels", "shopRelDtos").aElementType(ShopRel.class).bElementType(ShopRelDto.class).add()
.register();
mapperFactory.classMap(ShopRel.class, ShopRelDto.class)
.field("saleChannel.id", "channelId")
.field("saleChannel.name", "name")
.field("enabled", "enabled")
.register();
}
public static final void map(Object source, Object distance) {
mapper.map(source, distance);
}
public static final <T> T map(Object source, Class<T> destinationClass){
return mapper.map(source, destinationClass);
}
public static void main(String[] args) {
ShopEntity shop = new ShopEntity();
shop.setId(1L);
shop.setName("ABC");
ProductCategory productCategory =new ProductCategory();
productCategory.setId(10L);
shop.setMainCategory(productCategory);
Set<ShopRel> shopRels = new HashSet<>(0);
ShopSaleChannelRel channelRel = new ShopSaleChannelRel();
channelRel.setId(1L);
channelRel.setEnabled(true);
SaleChannel saleChannel = new SaleChannel();
saleChannel.setId(1L);
saleChannel.setName("Channel1");
channelRel.setSaleChannel(saleChannel);
shopRels.add(channelRel);
shop.setShopRels(shopRels);
ShopDto shopDto = map(shop, ShopDto.class);
System.out.println(shopDto);
}
}
It may need a custom mapping via customize if there is lot of cases like this you can extend Orika via Specifications to support this use case

Categories