Example usage for java.util NavigableMap lastEntry

List of usage examples for java.util NavigableMap lastEntry

Introduction

In this page you can find the example usage for java.util NavigableMap lastEntry.

Prototype

Map.Entry<K, V> lastEntry();

Source Link

Document

Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

Usage

From source file:Main.java

public static void main(String args[]) {
    Calendar now = Calendar.getInstance();
    Locale locale = Locale.getDefault();

    Map<String, Integer> names = now.getDisplayNames(Calendar.DAY_OF_WEEK, Calendar.LONG, locale);
    NavigableMap<String, Integer> nav = new TreeMap<String, Integer>(names);
    System.out.printf("Whole list:%n%s%n", nav);
    System.out.printf("Last key: %s\tLast entry: %s%n", nav.lastKey(), nav.lastEntry());
}

From source file:Main.java

public static void main(String[] args) {
    NavigableMap<String, Integer> navigableMap = new TreeMap<String, Integer>();
    String[] letters = { "a", "b", "c" };
    int[] ints = { 3, 2, 1 };
    for (int i = 0; i < letters.length; i++) {
        navigableMap.put(letters[i], ints[i]);
    }// w  w  w  .  j  a  v a 2s  . c om
    System.out.println("Map = " + navigableMap);
    System.out.println("Last entry = " + navigableMap.lastEntry());
}

From source file:com.streamsets.pipeline.hbase.api.common.processor.HBaseStore.java

private String getValue(HBaseColumn hBaseColumn, Result result) {
    String value = null;/* w  w  w.jav a  2  s. c  o  m*/
    if (result.isEmpty()) {
        return value;
    }
    if (hBaseColumn.getCf() == null || hBaseColumn.getQualifier() == null) {
        Map<String, String> columnMap = new HashMap<>();
        // parse column family, column, timestamp, and value
        for (Map.Entry<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> entry : result.getMap()
                .entrySet()) {
            String columnFamily = Bytes.toString(entry.getKey());
            for (Map.Entry<byte[], NavigableMap<Long, byte[]>> cells : entry.getValue().entrySet()) {
                String column = Bytes.toString(cells.getKey());
                NavigableMap<Long, byte[]> cell = cells.getValue();
                Map.Entry<Long, byte[]> v = cell.lastEntry();
                String columnValue = Bytes.toString(v.getValue());
                columnMap.put(columnFamily + ":" + column, columnValue);
            }
        }
        JSONObject json = new JSONObject(columnMap);
        value = json.toString();
    } else {
        value = Bytes.toString(result.getValue(hBaseColumn.getCf(), hBaseColumn.getQualifier()));
    }
    return value;
}

From source file:velocitekProStartAnalyzer.MainWindow.java

private void createChartPanel() {
    XYSeriesCollection dataset = JDBCPointDao.dataSet;
    JFreeChart chart = createChart(dataset);
    ChartPanel chartPanel = new ChartPanel(chart, true, false, false, true, false);
    chartPanel.setMinimumDrawWidth(0);//from   w w w.  java  2 s .  c o  m
    chartPanel.setMinimumDrawHeight(0);
    chartPanel.setMaximumDrawWidth(1920);
    chartPanel.setMaximumDrawHeight(1200);
    chartPanel.getPopupMenu().addSeparator();
    chartPanel.getPopupMenu().add(btnAvgSpeedChart);
    chartPanel.getPopupMenu().add(btnMedianSpeedChart);
    chartPanel.getPopupMenu().add(btnResetSpeedChart);
    chartPanel.getPopupMenu().addSeparator();
    btnMenuSaveSubmenuForChart = new JMenu("Save");
    chartPanel.getPopupMenu().add(btnMenuSaveSubmenuForChart);

    if (JDBCPointDao.points.isEmpty()) {
        btnSaveAsVCC.setEnabled(false);
    }
    saveChartAsPng(chartPanel);

    btnMenuSaveSubmenuForChart.add(btnSaveChartAsPngForChart);
    btnMenuSaveSubmenuForChart.add(btnSaveTableAsPngForChart);
    btnMenuSaveSubmenuForChart.add(btnSaveMapAsPngForChart);
    btnMenuSaveSubmenuForChart.addSeparator();
    btnMenuSaveSubmenuForChart.add(btnSaveAsVCC);
    chartPanel.addChartMouseListener(new ChartMouseListener() {

        @Override
        public void chartMouseClicked(ChartMouseEvent event) {
            Rectangle2D dataArea = chartPanel.getScreenDataArea();
            JFreeChart chart = event.getChart();
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis xAxis = plot.getDomainAxis();
            double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
            // make the crosshairs disappear if the mouse is out of range
            if (!xAxis.getRange().contains(x)) {
                x = Double.NaN;
            }

            x = Math.round(x);

            if (SwingUtilities.isLeftMouseButton(event.getTrigger()) && event.getTrigger().isShiftDown()) {
                for (PointDto cord : JDBCPointDao.points) {
                    {
                        if (cord.getPointID() == x) {
                            if (pointTable.getSelectionModel() == null) {
                                for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                    if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                        pointTable.setRowSelectionInterval(i, i);
                                    }
                                }
                            } else {
                                for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                    if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                        pointTable.addRowSelectionInterval(pointTable.getSelectedRow(), i);
                                    }
                                }
                            }
                            pointTable.scrollRectToVisible(
                                    pointTable.getCellRect(pointTable.getSelectedRow(), 0, true));
                        }
                    }
                }
            } else {
                for (PointDto cord : JDBCPointDao.points) {
                    {
                        if (cord.getPointID() == x) {
                            if (pointTable.getSelectionModel() != null) {
                                pointTable.getSelectionModel().clearSelection();
                            }
                            for (int i = 0; i < pointTable.getModel().getRowCount(); i++) {
                                if (pointTable.getModel().getValueAt(i, 0).equals(cord.getPointID())) {
                                    pointTable.setRowSelectionInterval(i, i);
                                }
                            }
                            pointTable.scrollRectToVisible(
                                    pointTable.getCellRect(pointTable.getSelectedRow(), 0, true));
                            //MainWindow.pointTable.revalidate();                      
                        }
                    }

                }
            }
        }

        @Override
        public void chartMouseMoved(ChartMouseEvent event) {

            Rectangle2D dataArea = chartPanel.getScreenDataArea();
            JFreeChart chart = event.getChart();
            XYPlot plot = (XYPlot) chart.getPlot();
            ValueAxis xAxis = plot.getDomainAxis();
            double x = xAxis.java2DToValue(event.getTrigger().getX(), dataArea, RectangleEdge.BOTTOM);
            // make the crosshairs disappear if the mouse is out of range
            if (!xAxis.getRange().contains(x)) {
                x = Double.NaN;
            }
            double y = DatasetUtilities.findYValue(plot.getDataset(), 0, x);
            xCrosshair.setValue(x);
            yCrosshair.setValue(y);
            x = Math.round(x);
            for (PointDto cord : JDBCPointDao.points) {

                if (cord.getPointID() == x) {
                    mapPanel.map().removeMapMarker(mapPanel.getMapPoint());
                    mapPanel.setMapPoint(
                            new MapMarkerDot(null, null, cord.getPointLatidude(), cord.getPointLongtidude()));
                    mapPanel.setMapPoint(mapPanel.getMapPoint());
                    mapPanel.getMapPoint().setColor(colorMapMarkerCircle);
                    mapPanel.getMapPoint().setBackColor(colorMapMarkerHover);
                    mapPanel.map().addMapMarker(mapPanel.getMapPoint());
                }

            }
        }

    });
    XYPlot xyPlot = (XYPlot) chart.getPlot();
    ValueAxis rangeAxis = xyPlot.getRangeAxis();
    NavigableMap<Double, PointDto> pointDtoSortedSpeedMap = new TreeMap<Double, PointDto>();

    if (!JDBCPointDao.points.isEmpty()) {
        for (PointDto pointDto : JDBCPointDao.points) {
            pointDtoSortedSpeedMap.put(pointDto.getPointSpeed(), pointDto);
        }
        rangeAxis.setRange(pointDtoSortedSpeedMap.firstEntry().getKey() - 0.1,
                pointDtoSortedSpeedMap.lastEntry().getKey() + 0.1);
    }

    CrosshairOverlay crosshairOverlay = new CrosshairOverlay();
    xCrosshair = new Crosshair(Double.NaN, Color.GRAY, new BasicStroke(0f));
    xCrosshair.setLabelVisible(true);
    yCrosshair = new Crosshair(Double.NaN, Color.GRAY, new BasicStroke(0f));
    yCrosshair.setLabelVisible(true);
    crosshairOverlay.addDomainCrosshair(xCrosshair);
    crosshairOverlay.addRangeCrosshair(yCrosshair);
    chartPanel.addOverlay(crosshairOverlay);
    graphPanel.removeAll();
    graphPanel.add(chartPanel, BorderLayout.CENTER);
    graphPanel.revalidate();
    graphPanel.repaint();
    graphMapSplitPanel.revalidate();
}

From source file:com.att.aro.core.packetanalysis.impl.VideoUsageAnalysisImpl.java

/**
 * <pre>/*from w ww  . j  a va 2 s.c  o m*/
 * Final pass to fix update values if not set already.
 * Examine startTime for each segment compared with next segment to determine duration when not set.
 *
 * Problems occur when there is a missing segment and on the last segment.
 *  Missing segments cause an approximation by dividing the duration by the number of missing segments+1
 *  The last segment simply repeats the previous duration, this should not skew results by much.
 */
private void updateDuration() {
    log.info("updateDuration()");
    if (videoUsage != null) {
        for (AROManifest manifest : videoUsage.getManifests()) {
            if (manifest != null) {
                NavigableMap<String, VideoEvent> eventMap = manifest.getSegmentEventList();
                if (manifest instanceof ManifestDash && !eventMap.isEmpty()) {
                    int seg = 0;
                    Entry<String, VideoEvent> lastEntry = eventMap.lastEntry();
                    double lastSeg = lastEntry != null ? lastEntry.getValue().getSegment() : 0;
                    String key = manifest.generateVideoEventKey(0, 0, "z");
                    Entry<String, VideoEvent> val;
                    Entry<String, VideoEvent> valn;
                    double duration = 0;
                    VideoEvent event;
                    String segNextKey = null;
                    for (seg = 1; seg <= lastSeg; seg++) {
                        segNextKey = manifest.generateVideoEventKey(seg, 0, "z");
                        val = eventMap.higherEntry(key);
                        valn = eventMap.higherEntry(segNextKey);
                        if (val == null || valn == null) {
                            break;
                        }
                        event = val.getValue();
                        VideoEvent eventNext = valn.getValue();
                        duration = eventNext.getSegmentStartTime() - event.getSegmentStartTime();
                        double deltaSegment = eventNext.getSegment() - event.getSegment();
                        if (deltaSegment > 1) {
                            duration /= deltaSegment;
                        }
                        updateSegmentDuration(eventMap, key, segNextKey, duration);
                        key = segNextKey;
                    }
                    // handle any segments at the end
                    val = eventMap.higherEntry(key);
                    if (val != null && segNextKey != null) {
                        updateSegmentDuration(eventMap, key, segNextKey, duration);
                    }
                }
            }
        }
    }
}

From source file:de.hybris.platform.acceleratorcms.services.impl.RankingCMSRestrictionService.java

@Override
public Collection<AbstractPageModel> evaluatePages(final Collection<AbstractPageModel> pages,
        final RestrictionData data) {
    final NavigableMap<Integer, List<AbstractPageModel>> allowedPages = new TreeMap<>();

    final Collection<AbstractPageModel> defaultPages = getDefaultPages(pages);
    for (final AbstractPageModel page : pages) {
        if (defaultPages.contains(page)) {
            continue;
        }/*from  w  ww .  j  a  v  a 2  s .c  om*/

        final List<AbstractRestrictionModel> restrictions = page.getRestrictions();
        if (restrictions == null || restrictions.isEmpty()) {
            LOG.debug("Page [" + page.getName()
                    + "] is not default page and contains no restrictions. Skipping this page.");
        } else {
            LOG.debug("Evaluating restrictions for page [" + page.getName() + "].");
            final boolean onlyOneRestrictionMustApply = page.isOnlyOneRestrictionMustApply();
            final boolean allowed = evaluate(restrictions, data, onlyOneRestrictionMustApply);
            if (allowed) {
                LOG.debug("Adding page [" + page.getName() + "] to allowed pages");
                final Integer countOfMatchingRestrictions = Integer
                        .valueOf(onlyOneRestrictionMustApply ? 1 : restrictions.size());

                if (allowedPages.containsKey(countOfMatchingRestrictions)) {
                    // Add to existing list
                    allowedPages.get(countOfMatchingRestrictions).add(page);
                } else {
                    // Add a new entry
                    final List<AbstractPageModel> list = new ArrayList<>();
                    list.add(page);
                    allowedPages.put(countOfMatchingRestrictions, list);
                }
            }
        }
    }

    final List<AbstractPageModel> result = new ArrayList<>();

    if (MapUtils.isNotEmpty(allowedPages)) {
        // Take the highest match count
        result.addAll(allowedPages.lastEntry().getValue());
    } else {
        if (defaultPages.size() > 1) {
            LOG.warn(createMoreThanOneDefaultPageWarning(defaultPages));
        }
        if (CollectionUtils.isNotEmpty(defaultPages)) {
            LOG.debug("Returning default page");
            result.add(defaultPages.iterator().next());
        }
    }

    return result;
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testLastEntry() {
    K[] keys = getSortedKeys();//  w  w w . j a  va 2s .  c o  m
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();

    // test with a single entry map
    map.put(keys[0], values[0]);
    assertEquals(keys[0], map.lastEntry().getKey());
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.lastEntry().getKey());
    assertEquals(keys[0], map.firstEntry().getKey());
    assertEquals(values[0], map.firstEntry().getValue());
    assertEquals(map.firstEntry().getKey(), map.lastEntry().getKey());

    // test with two entry map
    map.put(keys[1], values[1]);
    assertEquals(keys[1], map.lastEntry().getKey());
    assertFalse(keys[0].equals(map.lastEntry().getKey()));
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[1], map.lastEntry().getKey());
    Entry<K, V> entry = map.firstEntry();
    verifyEntry(entry);
    assertEquals(keys[0], entry.getKey());
    assertFalse(map.firstEntry().getKey().equals(map.lastEntry().getKey()));

    map.clear();
    assertNull(map.lastEntry());
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

/**
 * Test method for 'java.util.SortedMap.headMap(Object)' and
 * 'java.util.NavigableMap.headMap(Object, boolean)'.
 *
 * @see java.util.SortedMap#headMap(Object)
 * @see java.util.NavigableMap#headMap(Object, boolean)
 *//*w  ww.jav  a2s  .c o m*/
public void testHeadMap_entries_size() {
    // test with no entries
    K[] keys = getSortedKeys();
    assertEquals(0, createNavigableMap().headMap(keys[0]).size());

    NavigableMap<K, V> exclusiveHeadMap = createNavigableMap().headMap(keys[0], false);
    assertEquals(0, exclusiveHeadMap.size());
    assertNull(exclusiveHeadMap.firstEntry());
    assertNull(exclusiveHeadMap.lastEntry());
    try {
        assertNull(exclusiveHeadMap.firstKey());
        fail();
    } catch (NoSuchElementException e) {
        // expected outcome
    }
    try {
        assertNull(exclusiveHeadMap.lastKey());
        fail();
    } catch (NoSuchElementException e) {
        // expected outcome
    }

    NavigableMap<K, V> inclusiveHeadMap = createNavigableMap().headMap(keys[0], true);
    assertEquals(0, inclusiveHeadMap.size());
    assertNull(inclusiveHeadMap.firstEntry());
    assertNull(inclusiveHeadMap.lastEntry());
    try {
        assertNull(inclusiveHeadMap.firstKey());
        fail();
    } catch (NoSuchElementException e) {
        // expected outcome
    }
    try {
        assertNull(inclusiveHeadMap.lastKey());
        fail();
    } catch (NoSuchElementException e) {
        // expected outcome
    }
}

From source file:com.google.gwt.emultest.java.util.TreeMapTest.java

public void testFirstEntry() {
    K[] keys = getSortedKeys();/*  w w w .ja  v a2 s .  c  o m*/
    V[] values = getSortedValues();
    NavigableMap<K, V> map = createNavigableMap();

    // test with a single entry map
    map.put(keys[0], values[0]);
    assertEquals(keys[0], map.firstEntry().getKey());
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.firstEntry().getKey());
    assertEquals(keys[0], map.lastEntry().getKey());
    assertEquals(map.lastEntry().getKey(), map.firstEntry().getKey());

    // test with two entry map
    map.put(keys[1], values[1]);
    Entry<K, V> entry = map.firstEntry();
    verifyEntry(entry);
    assertEquals(keys[0], entry.getKey());
    assertFalse(keys[1].equals(map.firstEntry().getKey()));
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.firstEntry().getKey());
    assertFalse(keys[0].equals(map.lastEntry().getKey()));
    assertFalse(map.lastEntry().getKey().equals(map.firstEntry().getKey()));

    map.clear();
    assertNull(map.firstEntry());
}

From source file:org.apache.ctakes.ytex.kernel.SvmlinEvaluationParser.java

/**
 * support multi-class classification/*from w w  w. j  av a 2s  . c  o m*/
 * 
 * @param dataDir
 * @param outputDir
 * @param eval
 * @param fileBaseName
 * @param props
 * @param predict
 * @param listClassInfo
 * @throws IOException
 */
private void parseSvmlinOutput(File dataDir, File outputDir, SVMClassifierEvaluation eval, String fileBaseName,
        Properties props, List<InstanceClassInfo> listClassInfo, BiMap<Integer, String> classIdToNameMap)
        throws IOException {
    Properties codeProps = FileUtil
            .loadProperties(dataDir.getAbsolutePath() + "/" + fileBaseName + "code.properties", false);
    String[] codes = codeProps.getProperty("codes", "").split(",");
    SortedMap<String, double[]> codeToPredictionMap = new TreeMap<String, double[]>();
    if (codes.length == 0) {
        throw new IOException("invalid code.properties: " + fileBaseName);
    }
    // int otherClassId = 0;
    String otherClassName = null;
    if (codes.length == 1) {
        // otherClassId = Integer
        // .parseInt(codeProps.getProperty("classOther"));
        otherClassName = codeProps.getProperty("classOtherName");
    }
    for (String code : codes) {
        // determine class for given code
        // String strClassId = codeProps.getProperty(code+".class");
        // if (strClassId == null) {
        // throw new IOException("invalid code.properties: "
        // + fileBaseName);
        // }
        // int classId = Integer.parseInt(strClassId);
        String className = codeProps.getProperty(code + ".className");
        String codeBase = code.substring(0, code.length() - ".txt".length());
        // read predictions for given class
        codeToPredictionMap.put(className, readPredictions(
                outputDir.getAbsolutePath() + "/" + codeBase + ".outputs", listClassInfo.size()));
    }
    // iterate over predictions for each instance, figure out which class is
    // the winner
    String[] classPredictions = new String[listClassInfo.size()];
    for (int i = 0; i < listClassInfo.size(); i++) {
        if (otherClassName != null) {
            Map.Entry<String, double[]> classToPred = codeToPredictionMap.entrySet().iterator().next();
            classPredictions[i] = classToPred.getValue()[i] > 0 ? classToPred.getKey() : otherClassName;
        } else {
            NavigableMap<Double, String> predToClassMap = new TreeMap<Double, String>();
            for (Map.Entry<String, double[]> classToPred : codeToPredictionMap.entrySet()) {
                predToClassMap.put(classToPred.getValue()[i], classToPred.getKey());
            }
            classPredictions[i] = predToClassMap.lastEntry().getValue();
        }
    }
    boolean storeUnlabeled = YES.equalsIgnoreCase(props.getProperty(ParseOption.STORE_UNLABELED.getOptionKey(),
            ParseOption.STORE_UNLABELED.getDefaultValue()));
    updateSemiSupervisedPredictions(eval, listClassInfo, storeUnlabeled, classPredictions,
            classIdToNameMap.inverse());
}