This question already has answers here:
Java 8 stream map on entry set
(6 answers)
Closed 3 years ago.
I have such code:
Map<Integer, Settings> operatorsSettings = new HashMap<>();
operators.forEach((operator, codeTypes) -> operatorsSettings.put(operator, mapper.convertValue(codeTypes.get(SETTINGS), Settings.class)));
return operatorsSettings;
I wrote it but i wonder. Is it possible to write it without creating a new map. Something like this (not correct code):
return operators.entrySet().stream()
.collect(entry -> Collectors.toMap(entry.getKey() , mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));
It is possible, you just made a small syntax mistake...
return operators.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey() , mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));
Yes, you can do this in plain java:
return operators.entrySet().stream()
.collect(Collectors.toMap(entry -> entry.getKey() , entry -> mapper.convertValue(entry.getValue().get(SETTINGS), Settings.class)));
or you can use streamex library and write it like this:
EntryStream.of(operatorsSettings).mapValues(codeTypes -> mapper.convertValue(codeTypes.get(SETTINGS), Settings.class))...
Related
This question already has answers here:
Chaining Optionals in Java 8
(10 answers)
Closed 2 years ago.
public static BigDecimal calculateSomething(List<Type> myList, Optional<Type> secondOne) {
return myList.stream()
.findFirst()
.map(x -> x.getBalance().subtract(x.getAmount()))
.orElse(secondOne.map(x -> x.getBalance().subtract(x.getAmount()))
.orElse(BigDecimal.ZERO));
}
I want to do some mapping on firstOne from myList if it's present. If it's not I want to do same thing on the secondOne. If it's not present either then return ZERO.
Is there a way to write this inside of one stream and reduce code duplication and stream inside of the stream on Optional?
Yep:
return myList.stream().findFirst()
.or(() -> secondOne)
.map(x -> x.getBalance().subtract(x.getAmount()))
.orElse(BigDecimal.ZERO));
This question already has answers here:
Create only 1 list from a map where map value is list using JAVA 8 Streams
(3 answers)
Closed 4 years ago.
I have a
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
The type of value is a list of strings:
List<String> valueList = map.get('key');
How can i search through this map (through all the valueLists within this map) and get all the values which startsWith 'xy' in a list back?
I hope the question is clear.
I have tried this, but no success:
map
.entrySet()
.stream()
.filter(e-> e.getValue().stream().filter(value -> value.startsWith(searchString)))
.collect(Collectors.toList());
I get this error: Stream cannot be converted to boolean
If I understood your problem correctly:
map.values()
.stream()
.flatMap(List::stream)
.filter(x -> x.startsWith(searchString))
.collect(Collectors.toList())
This question already has answers here:
Java 8 is not maintaining the order while grouping
(2 answers)
Stream doesn't preserve the order after grouping
(3 answers)
Closed 4 years ago.
I've read many questions regarding Java 8 and Collections on this site and, given my limited understanding of java streams, I'm having some trouble trying to sort this Map.
My code is as follows, being tradeList an ArrayList();
Map<String, Double> buyReport = tradeList.stream().filter(trade -> trade.getInstruction() == Instruction.BUY)
.sorted(Comparator.comparing(trade -> trade.getInstructionDate()))
.collect(Collectors.groupingBy(trade -> dateFormat.format(trade.getInstructionDate()),
Collectors.summingDouble(trade -> trade.getUSDAmount())));
Does it make any sense to include the .sorted() statement when composing a HashMap? I tried to create a LinkedHashmap, use a custom comparator for the value i need the object instances to compare (a Double), but to no avail.
I can include any other piece of code you may find useful.
Thanks in advance!!
Update: tried this recently; still getting results unordered when grouping by company code and then summing company totals:
Map<String, Double> entityOutgoingReport = tradeList.stream()
.filter(trade -> trade.getInstruction() == Instruction.SELL)
.collect(Collectors.groupingBy(trade -> String.valueOf(trade.getEntity()),
LinkedHashMap::new,
Collectors.summingDouble(trade -> trade.getUSDAmount())));
for (String entity : entityOutgoingReport.keySet()) {
String key = entity;
String value = decFormat.format(entityOutgoingReport.get(entity));
tableBuilder.addRow(key, value); //Just pretty printing to console
}
Simply supply a LinkedHashMap into which the results will be inserted therefore maintaining order.
.collect(Collectors.groupingBy(trade ->
dateFormat.format(trade.getInstructionDate()),
LinkedHashMap::new,
Collectors.summingDouble(trade -> trade.getUSDAmount())));
Full code:
Map<String, Double> entityOutgoingReport =
tradeList.stream()
.filter(trade -> trade.getInstruction() == Instruction.SELL)
.sorted(Comparator.comparing(trade -> trade.getInstructionDate()))
.collect(Collectors.groupingBy(trade -> String.valueOf(trade.getEntity()),
LinkedHashMap::new,
Collectors.summingDouble(trade -> trade.getUSDAmount())));
This question already has answers here:
How do I keep the iteration order of a List when using Collections.toMap() on a stream?
(6 answers)
Closed 5 years ago.
I have the following hash map
Map<String,Double> map_1 = new LinkedHashMap<>();
with some keys: e.g. ["hello_1", "hello_2", "hello_3"].
Then, I iterate through these keys using stream API and saving new results in map2:
Map<String,Double> map_2 = new LinkedHashMap<>();
map_2 = map_1.keySet()
.stream()
.collect(
Collectors.toMap(entry -> entry,
entry -> {
Double value = map_1.get(entry);
return (value + 5);
}));
but the new hash map has keys in another order, despite it is defined as LinkedHashMap. I think the problem is during stream + collect steps.
Anyone could suggest me a solution?
Thanks
The order of the keys actually gets messed up in the collect step in this case.
You need to specify that you want to collect to a LinkedHashMap.
This question already has answers here:
Java 8 Collectors.toMap SortedMap
(5 answers)
Closed 7 years ago.
I have following code:
users.stream()
.sorted((u1, u2) -> u2.getScore().compareTo(u1.getScore()))
.limit(count)
.collect(Collectors.toMap((User::getName), (User::getScore)));
Content of result is right but when I want to foreach it - it output in unpredictable result. I think it is because under the hood HashMap is used.
Is there way to collect to mp with predictable result?
This works:
return users.stream()
.sorted((u1, u2) -> u2.getScore().compareTo(u1.getScore()))
.limit(count)
.collect(Collectors.toMap((User::getName), (User::getScore), (k, v) -> {
throw new RuntimeException(String.format("Duplicate key %s", k));
},
LinkedHashMap::new));