Saving value in a field using Java 8 - java-8

I have a list of callables
KNNQuery<O> knnq; //field
List<Callable<KNNQuery>> callables = Arrays.asList(
task1(database, relation),
task2(database, relation));
executor.invokeAll(callables) //List<Future<KNNQery>>
.stream() //stream<Future<KNNQuery>>
.map(future -> {
try{
return future.get();
}catch (Exception e){
throw new IllegalStateException(e);
}
}) //stream<KNNQuery>
.forEach(System.out::println);
Instead of printing output of two Futures to the screen i want to combing and save both future's output to the knnq field how can i do that?

You have to use a reducing operation to combine the stream elements.
A stream collect, that is the transformation of the stream elements into a specific accumulated result (List, Map, KNNQuery, and so for...) is a reducing operation.
Supposing that KNNQuery accepts a String parameter as constructor that is KNNQuery(String value) and you would like to combine the KNNQuery toString() value, you could do the following that uses the Collectors.joining() reduction :
KNNQuery<O> knnq =
new KNNQuery(
executor.invokeAll(callables) //List<Future<KNNQery>>
.stream() //stream<Future<KNNQuery>>
.map(future -> {
try{
return future.get();
}catch (Exception e){
throw new IllegalStateException(e);
}
})
.map(Object::toString)
.collect(Collectors.joining(","))
);
With Collectors.reducing() you would have more freedom to combine KNNQuery instances.
For example you could delegate it to a KNNQuery method : KNNQuery combine(KNNQuery other).
KNNQuery<O> knnq =
executor.invokeAll(callables) //List<Future<KNNQery>>
.stream() //stream<Future<KNNQuery>>
.map(future -> {
try{
return future.get();
}catch (Exception e){
throw new IllegalStateException(e);
}
})
.reducing(KNNQuery::combine) // add it to combine two KNNQuery instances
.orElse(null);

Related

How to add new Obect inside List<EntityClass>

I am fetching the record from the database. I want to modify new record with the existing record.
I fetching last 6 months data, I want to modify my result ? If any months records I am not getting from the database.
How I can modify existing result List ?
public List<EntityClassName> fetchByType() throws CustomExpection{
// TODO Auto-generated method stub
List<EntityClassName> result;
try {
result = (List<EntityClassName>) genDao.find(Query.byTpe, CommonUtil.getStartEndDate(), new BeanPropertyRowMapper(EntityClassName.class));
result.forEach(
userData -> {
String type = userData.getType_name();
log.info("Type:"+type);
//userData.setType_name(userData.getType_name()+" PPP");
}
);
log.info("Size:"+result.size());
System.err.println(result);
} catch (Exception e) {
e.printStackTrace();
log.error(
"Something went wrong !!!",
e.getMessage());
throw new CustomExpection("Something went wrong !!!");
}
return result;
}
List<Item> sBarang = new ArrayList<Item>();
Item mItem = new Item(); // <-- instantiate a new Item.
mItem.setCode("101");
mItem.setName("Hammer");
mItem.setQty(10);
sBarang.add(mItem); // <-- add it to your List<Item>.

I am accessing JSON array in streams , looking to handle if that JSON array is not present in the schema

JsonObject response = new JsonObject(IOUtils.resourceToString("/ResponseSample.json",
Charset.defaultCharset()));
JsonObject nameObj=
response.getJsonArray("applications",new JsonArray())
.stream().
map(JsonObject.class::cast)
.filter(x->x.getString("id").equalsIgnoreCase("2022025GSxxxxxx"))
.findFirst()
.get()
.getJsonArray("applicants",new JsonArray())
.getJsonObject(0)
.getJsonArray("names", new JsonArray())
.getJsonObject(0)
.getJsonObject("name",new JsonObject());
System.out.println(nameObj.getString("first","")+"--"+nameObj.getString("last",""));
} catch (IOException ex) {
ex.printStackTrace();
}

java stream is making weird things to generate csv file in Spring Boot

I'm processing a csv file through my springboot app, the file is to download it, in my case I use streams but there is a problem what I don't know what's wrong in my code because some rows is complete with the columns but next row only write some columns and leftover columns are write below as if were a new row. I hope you understand what I mean. I hope you give a hand, thank you in advance.
This code below is the controller
.....
#RequestMapping(value="/stream/csv/{grupo}/{iduser}", method = RequestMethod.GET)
public void generateCSVUsingStream(#PathVariable("grupo") String grupo,
#PathVariable("iduser") String userId,HttpServletResponse response) {
response.addHeader("Content-Type", "application/csv");
response.addHeader("Content-Disposition", "attachment; filename=\""+userId+"_Reporte_PayCash"+grupo.replaceAll("\\s", "")+".csv");
response.setCharacterEncoding("UTF-8");
try (Stream<ReportePayCashDTO> streamPaycashdatos = capaDatosDao.ReportePayCashStream(userId, grupo);PrintWriter out = response.getWriter();) {
//PrintWriter out = response.getWriter();
out.write(String.join(",", "Cuenta" , "Referencia", "Referencia_paycash","Distrito","Plaza","Cartera"));
out.write("\n");
streamPaycashdatos.forEach(streamdato -> {
out.write(streamdato.getAccount()+","+streamdato.getReferencia()+","+streamdato.getReferenciapaycash()
+","+streamdato.getCartera()+","+streamdato.getState()+","+streamdato.getCity());
out.append("\r\n");
});
out.flush();
out.close();
streamPaycashdatos.close();
} catch (IOException ix) {
throw new RuntimeException("There is an error while downloading file", ix);
}
}
The method on DAO is this
...
#Override
public Stream<ReportePayCashDTO> ReportePayCashStream(String userId, String grupo) {
// TODO Auto-generated method stub
Stream<ReportePayCashDTO > stream = null ;
String query ="";
//more code
try {
stream = getJdbcTemplate().queryForStream(query, (rs, rowNum) -> {
return new ReportePayCashDTO(Utils.valnull(rs.getString("account")),
Utils.valnull(rs.getString("reference")),
Utils.valnull(rs.getString("referencepaycash")),
Utils.valnull(rs.getString("state")),
Utils.valnull(rs.getString("city")),
Utils.valnull(rs.getString("cartera"))
);
});
}catch(Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
}
return stream;
}
Example: This is what I hoped will write into csv file
55xxxxx02,88xxxx153,1170050202662,TAMAULIPAS,TAMPICO,AmericanExpre
58xxxxx25,88xxx899,1170050202662,TAMAULIPAS,TAMPICO,AmericanClasic
but some rows was written like this
55xxxxx02,88xxxx153,1170050202662
,TAMAULIPAS,TAMPICO,AmericanExpre
58xxxxx25,88xxx899,1170050202662
,TAMAULIPAS,TAMPICO,AmericanClasic

java 8 Stream to map

I want to convert the following into functional program. Please help to stream line the below code.
Map <String, TreeSet<Double>> cusipMap = new HashMap<>();
String[] key = new String[1];
try {
Files.lines(Paths.get("C:\\CUSIP.txt")).
forEach(l -> {
if (isCUSIP(l)) {
if (cusipMap.get(l) == null )
cusipMap.put(l, new TreeSet<Double>());
key[0] = l;
} else {
cusipMap.get(key[0]).add(Double.valueOf(l));
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this one
try {
Map<String, TreeSet<Double>> result = Files.lines(Paths.get("C:\\CUSIP.txt"))
.collect(Collectors.groupingBy(Function.identity(), Collector.of(
TreeSet::new,
(TreeSet<Double> tree, String s) -> {tree.add(Double.valueOf(s));},
(TreeSet<Double> tree, TreeSet<Double> s) -> {tree.addAll(s); return tree;}
)));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Transform Optional String and return Date in Java 8?

I am currently parsing a nullable String to a Date. I try to use Optional to avoid using if statement. Here is what I have written so far :
Client client = new Client();
Optional.ofNullable(methodThatMayReturnStringOrNull())
.ifPresent((s) -> {
try {
client.setBirthDate(DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
Is it possible to transform this lambda so I can make it a method similar to the following but java 8 style?
private Date parse(String complexString) {
Date birthDate = null;
if (complexString != null) {
try {
birthDate = DateUtils.parseDate(
StringUtils.substring(complexString, 0, 10),
new String[]{"yyyy-MM-dd"});
} catch (final ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
}
return birthDate;
}
Not sure how far you want to go, but you can start with
Optional<Date> date = Optional.ofNullable(methodThatMayReturnStringOrNull())
.map((s) -> {
try {
return DateUtils.parseDate(
StringUtils.substring(s, 0, 10),
new String[]{"yyyy-MM-dd"}));
} catch (ParseException e) {
throw new TechnicalException("error.parsing.date", e);
}
});
You might also consider using flatMap instead of map and returning empty optional instead of throwing exception on error - depends on how you want to progress you flow.
On completely unrelated note, get rid of Date and use either joda or new java time classes ;)

Resources