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 ?
Related
I have an Arraylist named deleteFields.
I have an Object named mergedDiffSRO.
I have to delete all the fields of mergedDiffSRO which are present in deleteFields.
LeadDetailsSRO mergedDiffSRO = new LeadDetailsSRO();
public class LeadDetailsSRO{
private String emailId;
private String emailByCompany;
private int level;
private LeadObjects leadobj;
private String alternateNumber;
private String languagePreference;
private String kycName;
private String businessAs;
private String aadharName;
private String panName;
private String ovdName;
private String kycStatus;
private String aadhaarStatus;
private String panStatus;
private Set<String> ownershipTypeSet;
private String empId;
private String designation;
private Boolean nameMatchSuccess = null;
private String isSIMandatory;
}
List<String> deleteFields = new ArrayList<String>();
deleteFields.add("businessAs");
deleteFields.add("empId");
deleteFields.add("designation");
deleteFields.add("emailByCompany");
deleteFields.add("level");
deleteFields.add("ovdName");
How do i proceed with the same?
Is reflection to be used for the same?
Please suggest some way out with proper code in JAVA.
You can do it with reflection. But that's ugly, slow and error-prone. So, here it is:
public void deleteFieldsByName(LeadDetailsSRO details, List<String> fieldNames) throws Exception {
for (String fieldName : fieldNames) {
Field field = LeadDetailsSRO.class.getDeclaredField(fieldName);
// this is usually not allowed at production settings
field.setAccessible(true);
Class fieldType = field.getType();
// the following if-else is ugly.
// But that's what we can do. We have to differentiate by classes.
if (fieldType.equals(String.class)) {
field.set(details, null);
} else if (fieldType.equals(Set.class)) {
field.set(details, new HashSet<>());
} else if (fieldType.toString().equals("int")) {
field.set(details, 0);
}
}
I suggest that you look for other kind of solutions.
Update
We can do it without reflection too. This is still ugly and error-prone. But at least, it's fast and it will work in prod environments too:
public class LeadDetailsSRO {
private String emailId;
private String emailByCompany;
private int level;
private String alternateNumber;
private String languagePreference;
private String kycName;
private String businessAs;
private String aadharName;
private String panName;
private String ovdName;
private String kycStatus;
private String aadhaarStatus;
private String panStatus;
private Set<String> ownershipTypeSet;
private String empId;
private String designation;
private Boolean nameMatchSuccess = null;
private String isSIMandatory;
public void deleteFields(List<String> fields) {
for (String fieldName : fields) {
switch (fieldName) {
case "emailId":
this.emailId = null;
break;
case "emailByCompany":
this.emailByCompany = null;
break;
// ...
}
}
}
}
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).
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
i have a java enum which have to have some default values like
for the
String some default values
int some degault values
etc
i have created a enum like the following
package com.hexgen.tools;
public enum DefaultParamsValues {
STRING ("HEXGEN"),
INTEGER(2013),
DATE(new org.joda.time.LocalDate()),
BOOLEAN(true),
BIGINTEGER(BigInteger.valueOf(Long.MAX_VALUE)),
LONG("1898.48");
private String defaultString;
private int defaultInteger;
private LocalDate defaultDate;
private boolean defaultBoolean;
private long defaultLong;
private BigInteger defaultBigInteger;
public DefaultParamsValues(String strValue,int intValue,LocalDate date,boolean booleanValue,long longValue,BigInteger bigintVlaue){
this.defaultString = strValue;
this.defaultInteger = intValue;
this.defaultDate = date;
this.defaultBoolean = booleanValue;
this.defaultLong=longValue;
this.defaultBigInteger = bigintVlaue;
}
}
but it is giving so many issues, would some one help me to create a enum with basic values for primitive types?
EDIT: this is how i solved it:
package com.test.poc;
import java.math.BigInteger;
import org.joda.time.LocalDate;
public enum DefaultParamValues {
STRING("HEXGEN"),
INTEGER(123),
DATE(new LocalDate()),
BOOLEAN(true),
LONGVALUE(123123),
BIGINTEGER(BigInteger.valueOf(Long.MAX_VALUE));
private String defaultString;
private int defaultInteger;
private LocalDate defaultDate;
private boolean defaultBoolean;
private long defaultLong;
private BigInteger defaultBigInteger;
private DefaultParamValues(String strDefaultValue) {
defaultString = strDefaultValue;
}
private DefaultParamValues(int intDefaultValue) {
defaultInteger = intDefaultValue;
}
private DefaultParamValues(LocalDate dateDefaultValue) {
defaultDate = dateDefaultValue;
}
private DefaultParamValues(boolean booleanDefaultValue) {
defaultBoolean = booleanDefaultValue;
}
private DefaultParamValues(long longDefaultValue) {
defaultLong = longDefaultValue;
}
private DefaultParamValues(BigInteger bigIntegerDefaultValue) {
defaultBigInteger = bigIntegerDefaultValue;
}
public String getDefaultString() {
return defaultString;
}
public int getDefaultInt() {
return defaultInteger;
}
public LocalDate getDefaultDate() {
return defaultDate;
}
public boolean getDefaultBoolean() {
return defaultBoolean;
}
public long getDefaultLong() {
return defaultLong;
}
public BigInteger getDefaultBigInteger() {
return defaultBigInteger;
}
}
Thanks
First, an enum is probably not right for your purpose. You should use a final Class with constants.
But if you want it inefficient and cumbersome you could do it this way:
public enum GenericEnum {
STRING("HEXGEN"),
INTEGER(2013),
DATE(new Date()),
BOOLEAN(true),
BIGINTEGER(BigInteger.valueOf(Long.MAX_VALUE)),
LONG("1898.48");
private String defaultString;
private int defaultInteger;
private Date defaultDate;
private boolean defaultBoolean;
private long defaultLong;
private BigInteger defaultBigInteger;
GenericEnum(Object value) {
if(String.class.isAssignableFrom(value.getClass())) {
this.defaultString = (String) value;
} else if (Integer.class.isAssignableFrom(value.getClass())) {
this.defaultInteger = (Integer) value;
}
[...]
}
}
or overload the constructor:
private GenericEnum(String val) {
this.defaultString = val;
}
private GenericEnum(int val) {
this.defaultInteger = val;
}
[...]
I have the json return from server like this:
[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]
how to I get the arrays group and subgroup?
I'm using restlet on Android Client.
thanks all.
String mResponse = "[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]";
JSONArray responseArrayJson = new JSONArray(mResponse); // This creates a JSON array from your response string.
JSONObject objectJson = responseArrayJson.getJSONObject(0); // gets the one and only JSON object in your array.
JSONArray groupArrayJson = objectJson.getJSONArray("group"); // gets the array indexed by "group".
You can repeat this pattern to get "subGroup" as well.
I solved this problem as follows:
first change the json of server:
from:
[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]
to
{"array":[{"id":1,"group":[{"id":1,"subGroup":[{"id":1,"item":"X"}]}]}]}
Second in Android client I make this:
a class to get first array, the class ServerModel with firstArray "array":
public class ServerModel implements Serializable {
private static final long serialVersionUID = 1L;
private FirstArray[] array;
public ServerModel() {
}
public ServerModel(FirstArray[] array) {
this.array = array;
}
}
third the class with secondArray "group":
public class FirstArray implements Serializable {
private static final long serialVersionUID = 1L;
private SecondArray[] group;
private int id;
public FirstArray() {
}
public FirstArray(int id, SecondArray[] group) {
this.id = id;
this.group = group;
}
}
fourth the class with thirdArray "subGroup":
public class SecondArray implements Serializable {
private static final long serialVersionUID = 1L;
private Itens[] subGroup;
private int id;
public SecondArray() {
}
public SecondArray(int id, Itens[] subGroup) {
this.id = id;
this.subGroup = subGroup;
}
}
and in the last the class of itens "item"
public class Itens implements Serializable {
private static final long serialVersionUID = 1L;
private String item;
private int id;
public Itens() {
}
public Itens(int id, String item) {
this.id = id;
this.item = item;
}
}
thanks all for help!!!