I want to convert the code from Java 1.8 to Java 1.6, is there somebody who can help me on this?
// Sort map
Map<String, JMap9200StatBase.Record> sortedMap = resultMap.getMap().entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(oldValue, newValue) -> oldValue, LinkedHashMap::new));
I am looking for the equivalent Java 1.6 code for the above Java 1.8 code.
Related
I have the following code
TermVectorsResponse resp = request.execute().actionGet();
XContentBuilder builder = XContentFactory.jsonBuilder();
resp.toXContent(builder, null);
Map<String, Object> map = XContentHelper.convertToMap(builder.bytes(), false, XContentType.JSON).v2();
return map;
and my compiler is complaining because it cannot resolve the method bytes() for XContentBuilder. My code worked for elasticsearch 6.2.2 and I know the error of the compiler is because in elasticsearch 7.5 the method bytes() was removed. So, how I'm I suppose to create the map variable, I've looked everywhere and I haven't find an answer. I guess I'm supposed to create a JsonXContent and use it instead the builder.bytes() or retrieve the bytes another way but I don't know for sure
Thanks in advance
the builder.bytes() is like a kind of anti pattern so you can get a BytesReference from your builder using:
BytesReference.bytes(builder)
example for 7.6:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-put-stored-script.html
I got stuck with this problem.
I've found similar answers here, but none of those solves the problem.
Should I use mapToDouble() here? Is there anything like "mapToDoubleArray"?
To convert a List<List<Double>> into a List<double[]>, you need to map each inner list into a double array using mapToDouble combined with toArray() (which is the "mapToDoubleArray" operation you are looking for).
List<double[]> res =
myList.stream()
.map(l -> l.stream().mapToDouble(d -> d).toArray())
.collect(toList());
If you want a List<Double[]> instead, you can simply use .map(list -> list.toArray(new Double[list.size()])).
I need to convert these code into Java 8 Stream I tried it using the given below code written by me but still I haven't got what I wanted.
//contractList is list of Contract class
//contract.getProgramId() returns String
//contract.getEnrollmentID() returns String
//'usage = CommonUtils.getUsageType()' is other service to call wich returns String
//enroll and usage are String type
//enrollNoWithUsageTypeJson is json object '{"enroll": value, "usage": value}'
//usages is List<JSONObject> where enrollNoWithUsageTypeJson need to add
for (Contract contract : contractList) {
if (!StringUtils.isEmpty(contract.getProgramId())) {
enroll = contract.getEnrollmentID();
usage = CommonUtils.getUsageType(envProperty, contract.getProgramId());
if (!(StringUtils.isEmpty(enroll) || StringUtils.isEmpty(usage))) {
enrollNoWithUsageTypeJson.put("enroll", enroll);
enrollNoWithUsageTypeJson.put("usage", usage);
usages.add(enrollNoWithUsageTypeJson);
}
}
}
This is till now what I have got:
contractList.stream()
.filter(contract -> !StringUtils.isEmpty(contract) &&
!StringUtils.isEmpty(contract.getProgramId()))
.collect(Collectors.to);
Thakyou in advance :)
Here is how a stream based version of your code might look like (add static imports as needed):
List<JSONObject> usages = contractList.stream()
.filter(c -> isNotEmpty(c.getProgramId()))
.map(c -> new SimpleEntry<>(c.getEnrollmentID(), getUsageType(envProperty, c.getProgramId())))
.filter(e -> isNotEmpty(e.getKey()) && isNotEmpty(e.getValue())))
.map(e -> {
enrollNoWithUsageTypeJson.put("enroll", e.getKey());
enrollNoWithUsageTypeJson.put("usage", e.getValue());
return enrollNoWithUsageTypeJson; })
.collect(toList());
I took the liberty of using isNotEmpty from Apache Commons as given this option !isEmpty looks terrible. I am (ab)using AbstractMap.SimpleEntry to hold a pair of values. If you feel getKey, getValue make the code less readable, you can introduce a class to hold these 2 variables. E.g.:
class EnrollUsage {
String enroll, usage;
}
You may also prefer to define a method:
JSONObject withEnrollAndUsage(JSONObject json, String enroll, String usage) {
json.put("enroll", enroll);
json.put("usage", usage);
return json;
}
and in the above use instead:
.map(e -> withEnrollAndUsage(enrollNoWithUsageTypeJson, e.getKey(), e.getValue()))
Keep in mind that you never really "need" to convert code to use streams. There are cases where using streams, albeit intellectually satisfying, actually complicates your code. Exercise your best judgement in this case.
I'm trying to implement (A, B) => Unit from Java code. How do I return a value for Unit?
Unit is the scala equivalent of void in Java, so there's no need to return anything.
I am currently having some issues in trying to sort a Map<String, IncreaseDetails>, where IncreaseDetails is simply a custom data structure holding a few fields.
So far I have understood fairly clearly that using a TreeMap is heavily discouraged as a TreeMap should be sorted by the KeySet rather than the actual values.
I have therefore tried to switch to both HashMap and LinkedHashMap but simply calling
Collections.sort(map,comparator) doesn't seem to do the trick. Since Java 8 I was planning on trying to use the Stream API, but I don't really know it too well.
So far my comparator looks like this:
import java.util.Comparator;
import java.util.Map;
public class CompTool implements Comparator<Float> {
Map<String, IncreaseDetails> unsortedMap;
public CompTool(Map<String, IncreaseDetails> unsortedMap)
{
this.unsortedMap = unsortedMap;
}
public int compare(Float countryOne, Float countryTwo)
{
Float countryOneValue = unsortedMap.get(countryOne).getRealIncrease();
Float countryTwoValue = unsortedMap.get(countryTwo).getRealIncrease();
return countryTwoValue.compareTo(countryOneValue);
}
}
Any suggestion would be very much welcome, as I have found a lot of similar questions or videos but none too useful for my current situation.
Your question is somewhat unclear. I assume that you want to sort the unsortedMap entries by the value stored in getRealIncrease in reversed order. This can be done by creating the stream of original map entries, sorting and collecting the result into the LinkedHashMap, which preserves insertion order:
Map<String, IncreaseDetails> sortedMap = unsortedMap.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(
(Comparator.comparing(IncreaseDetails::getRealIncrease).reversed())))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new));