下面列出了java.util.HashMap#computeIfPresent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private List<Integer> reorderBooks(final List<Integer> books) {
// Counting how often a book number appears in the basket list
HashMap<Integer, Integer> numberCount = new HashMap<>();
for (Integer book : books) {
numberCount.computeIfPresent(book, (key, value) -> value + 1);
numberCount.putIfAbsent(book, 1);
}
return books.stream()
.sorted((bookNumberOne, bookNumberTwo) -> {
Integer countOne = numberCount.get(bookNumberOne);
Integer countTwo = numberCount.get(bookNumberTwo);
// Books whose numbers appear more often should be in front of the basket list
if (countOne > countTwo) {
return -1;
} else if (countOne.equals(countTwo)) {
return 0;
} else {
return 1;
}
})
.collect(Collectors.toList());
}
private List<Object> processDuplicates(List<Object> iterations)
{
// since the user can decide to annotate the same data set several times to the same function we need to care
// about the duplicates. First of all we need to clone those objects, then we need to set a special index which
// will be later used to distinguish them in the run
// this map contains the counter for the new index
HashMap<Object, Integer> iterationIndexMap = new HashMap<>();
List<Object> fixedIterations = new LinkedList<>();
for (Object object : iterations)
{
if (!fixedIterations.contains(object))
{
// no duplicate, just add it
fixedIterations.add(object);
}
else
{
// now the funny part, we encountered an duplicated object
// always set the first occurrence of an object to 1
TestdataStatementData existingObject = (TestdataStatementData) object;
existingObject.setIterationIndex(1);
// set the counter for this object to 1
iterationIndexMap.computeIfAbsent(object, (o) -> {
return 1;
});
// increment the counter every time we visit with the same object
Integer newIndex = iterationIndexMap.computeIfPresent(object, (o, index) -> {
return (index + 1);
});
// important: we clone that object
TestdataStatementData clonedObject = new TestdataStatementData((TestdataStatementData) object);
// set the "iteration" index to the new cloned object
clonedObject.setIterationIndex(newIndex);
// add it to the list
fixedIterations.add(clonedObject);
}
}
return fixedIterations;
}