Java Code Examples for java.util.HashMap#computeIfPresent()
The following examples show how to use
java.util.HashMap#computeIfPresent() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BookStore.java From java with MIT License | 6 votes |
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()); }
Example 2
Source File: TestdataStatement.java From neodymium-library with MIT License | 4 votes |
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; }