Example usage for java.util OptionalInt isPresent

List of usage examples for java.util OptionalInt isPresent

Introduction

In this page you can find the example usage for java.util OptionalInt isPresent.

Prototype

boolean isPresent

To view the source code for java.util OptionalInt isPresent.

Click Source Link

Document

If true then the value is present, otherwise indicates no value is present

Usage

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(6, 5, 7, 1, 2, 3, 3);
    OptionalInt d = i.min();
    if (d.isPresent()) {
        System.out.println(d.getAsInt());
    } else {//from w  ww.  j a  v a  2 s . com
        System.out.println("no value");
    }
}

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(6, 5, 7, 1, 2, 3, 3);
    OptionalInt d = i.max();
    if (d.isPresent()) {
        System.out.println(d.getAsInt());
    } else {//from  ww  w.jav  a 2s  . com
        System.out.println("no value");
    }
}

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(1, 2, 3, 4);
    OptionalInt n = i.findAny();
    if (n.isPresent()) {
        System.out.println(n.getAsInt());
    } else {/* w  w  w.  j  a v  a 2s  .  co  m*/
        System.out.println("noValue");
    }
}

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(1, 2, 3, 4);
    OptionalInt n = i.findFirst();
    if (n.isPresent()) {
        System.out.println(n.getAsInt());
    } else {/*from  w  w  w.j  a  v  a 2 s .co  m*/
        System.out.println("noValue");
    }
}

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(6, 5, 7, 1, 2, 3, 3);
    OptionalInt v = i.reduce(Integer::sum);
    if (v.isPresent()) {
        System.out.println(v.getAsInt());
    } else {/*from  w w  w  .j  av a 2s .  c  om*/
        System.out.println(v);
    }

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Dish.Type.MEAT),
            new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT),
            new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER),
            new Dish("prawns", false, 400, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH));
    List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);

    Arrays.stream(numbers.toArray()).forEach(System.out::println);
    // max and OptionalInt
    OptionalInt maxCalories = menu.stream().mapToInt(Dish::getCalories).max();
    System.out.println("Number of calories:" + maxCalories);

    int max;/*from w  w w  . j  a v  a  2s.  com*/
    if (maxCalories.isPresent()) {
        max = maxCalories.getAsInt();
    } else {
        // we can choose a default value
        max = 1;
    }
    System.out.println(max);
}

From source file:net.minecraftforge.oredict.DyeUtils.java

/**
 * Get the dye damage from the stack, which can be passed into {@link EnumDyeColor#byDyeDamage(int)}.
 * @param stack the item stack//  www . j av a  2 s  . co  m
 * @return an {@link OptionalInt} holding the dye damage for a dye, or an empty {@link OptionalInt} otherwise
 */
public static OptionalInt dyeDamageFromStack(ItemStack stack) {
    final OptionalInt meta = metaFromStack(stack);
    return meta.isPresent() ? OptionalInt.of(0xF - meta.getAsInt()) : OptionalInt.empty();
}

From source file:net.minecraftforge.oredict.DyeUtils.java

/**
 * Get a dye's color./*from   ww w  . j a  v  a 2  s .c  o m*/
 * @param stack the item stack
 * @return an {@link Optional} holding the dye color if present, or an empty {@link Optional} otherwise
 */
public static Optional<EnumDyeColor> colorFromStack(ItemStack stack) {
    final OptionalInt meta = metaFromStack(stack);
    return meta.isPresent() ? Optional.of(EnumDyeColor.byMetadata(meta.getAsInt())) : Optional.empty();
}

From source file:com.diversityarrays.kdxplore.trials.AddScoringSetDialog.java

public AddScoringSetDialog(Window owner, KdxploreDatabase kdxdb, Trial trial,
        Map<Trait, List<TraitInstance>> instancesByTrait, SampleGroup curatedSampleGroup) {
    super(owner, Msg.TITLE_ADD_SCORING_SET(), ModalityType.APPLICATION_MODAL);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.kdxploreDatabase = kdxdb;
    this.trial = trial;
    this.curatedSampleGroupId = curatedSampleGroup == null ? 0 : curatedSampleGroup.getSampleGroupId();

    Map<Trait, List<TraitInstance>> noCalcs = instancesByTrait.entrySet().stream()
            .filter(e -> TraitDataType.CALC != e.getKey().getTraitDataType())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    Map<Trait, List<TraitInstance>> noCalcsSorted = new TreeMap<>(TRAIT_COMPARATOR);
    noCalcsSorted.putAll(noCalcs);/*  w w  w .ja  v  a2  s .  c o m*/

    BiFunction<Trait, TraitInstance, String> parentNameProvider = new BiFunction<Trait, TraitInstance, String>() {
        @Override
        public String apply(Trait t, TraitInstance ti) {
            if (ti == null) {
                List<TraitInstance> list = noCalcsSorted.get(t);
                if (list == null || list.size() != 1) {
                    OptionalInt opt = traitInstanceChoiceTreeModel.getChildChosenCountIfNotAllChosen(t);
                    StringBuilder sb = new StringBuilder(t.getTraitName());

                    if (opt.isPresent()) {
                        // only some of the children are chosen
                        int childChosenCount = opt.getAsInt();
                        if (childChosenCount > 0) {
                            sb.append(" (").append(childChosenCount).append(" of ").append(list.size())
                                    .append(")");
                        }
                    } else {
                        // all of the children are chosen
                        if (list != null) {
                            sb.append(" (").append(list.size()).append(")");
                        }
                    }
                    return sb.toString();
                }
            }
            return t.getTraitName();
        }
    };

    Optional<List<TraitInstance>> opt = noCalcsSorted.values().stream().filter(list -> list.size() > 1)
            .findFirst();
    String heading1 = opt.isPresent() ? "Trait/Instance" : "Trait";

    traitInstanceChoiceTreeModel = new ChoiceTreeTableModel<>(heading1, "Use?", //$NON-NLS-1$
            noCalcsSorted, parentNameProvider, childNameProvider);

    //        traitInstanceChoiceTreeModel = new TTChoiceTreeTableModel(instancesByTrait);

    traitInstanceChoiceTreeModel.addChoiceChangedListener(new ChoiceChangedListener() {
        @Override
        public void choiceChanged(Object source, ChoiceNode[] changedNodes) {
            updateCreateAction("choiceChanged");
            treeTable.repaint();
        }
    });

    traitInstanceChoiceTreeModel.addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeStructureChanged(TreeModelEvent e) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent e) {
        }

        @Override
        public void treeNodesInserted(TreeModelEvent e) {
        }

        @Override
        public void treeNodesChanged(TreeModelEvent e) {
            updateCreateAction("treeNodesChanged");
        }
    });

    warningMsg.setText(PLEASE_PROVIDE_A_DESCRIPTION);
    warningMsg.setForeground(Color.RED);

    Container cp = getContentPane();

    Box sampleButtons = null;
    if (curatedSampleGroup != null && curatedSampleGroup.getAnyScoredSamples()) {
        sampleButtons = createWantSampleButtons(curatedSampleGroup);
    }

    Box top = Box.createVerticalBox();
    if (sampleButtons == null) {
        top.add(new JLabel(Msg.MSG_THERE_ARE_NO_CURATED_SAMPLES()));
    } else {
        top.add(sampleButtons);
    }
    top.add(descriptionField);

    cp.add(top, BorderLayout.NORTH);

    descriptionField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }
    });

    updateCreateAction("init");
    //        KDClientUtils.initAction(ImageId.`CHECK_ALL, useAllAction, "Click to Use All");

    treeTable = new JXTreeTable(traitInstanceChoiceTreeModel);
    treeTable.setAutoResizeMode(JXTreeTable.AUTO_RESIZE_ALL_COLUMNS);

    TableCellRenderer renderer = treeTable.getDefaultRenderer(Integer.class);
    if (renderer instanceof JLabel) {
        ((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);
    }

    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(useAllAction));
    buttons.add(new JButton(useNoneAction));

    buttons.add(Box.createHorizontalGlue());
    buttons.add(warningMsg);

    buttons.add(new JButton(cancelAction));
    buttons.add(Box.createHorizontalStrut(10));
    buttons.add(new JButton(createAction));

    cp.add(new JScrollPane(treeTable), BorderLayout.CENTER);
    cp.add(buttons, BorderLayout.SOUTH);

    pack();
}

From source file:oct.analysis.application.comp.EZWorker.java

@Override
protected EZEdgeCoord doInBackground() throws Exception {
    int foveaCenterXPosition = analysisManager.getFoveaCenterXPosition();
    /*/*from ww  w .j  a v  a2 s . c  om*/
     first get a sharpened version of the OCT and use that to obtain the segmentation
     of the Bruch's membrane. Use a Loess interpolation algorithm to smooth 
     out imperfetions in the segmentation line.
     */
    UnivariateInterpolator interpolator = new LoessInterpolator(0.1, 0);
    ArrayList<Point> rawBrmPoints = new ArrayList<>(analysisManager
            .getSegmentation(new SharpenOperation(15, 0.5F)).getSegment(Segmentation.BrM_SEGMENT));
    double[][] brmSeg = Util.getXYArraysFromPoints(rawBrmPoints);
    UnivariateFunction brmInterp = interpolator.interpolate(brmSeg[0], brmSeg[1]);
    BufferedImage sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F);
    setProgress(10);
    /*
     Starting from the identified location of the fovea search northward in 
     the image until the most northern pixels northward (in a 3x3 matrix of 
     pixels arround the the search point (X,Y) ) are black (ie. the search
     matrix is has found that the search point isn't totally surrounded by
     white pixels). Then a recursive search algorithm determines if the 
     black area signifies the seperation between bands or simply represents
     a closed (a black blob entirely surrounded by white pixels) black band.
     It will continue searching northward in the image until it can find an 
     open region of all blak pixels. Once this is found it will find the contour
     of the edge between the black and white pixels along the width of the image.
     */
    int searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition)) + 1;
    do {
        searchY--;
    } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
            || !isContrastPoint(foveaCenterXPosition, searchY, sharpOCT));
    LinkedList<Point> contour = new LinkedList<>();
    Point startPoint = new Point(foveaCenterXPosition, searchY);
    //find contour by searching for white pixel boundary to te right of the fovea
    contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour,
            sharpOCT, 0));
    //search until open black area found (ie. if the search algorithm arrives back at
    //the starting pixel keep moving north to next black area to search)
    while (contour.get(0).equals(startPoint)) {
        contour = new LinkedList<>();
        do {
            searchY--;
        } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0);
        do {
            searchY--;
        } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
                || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
        startPoint = new Point(foveaCenterXPosition, searchY);
        contour.add(findContourRight(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour,
                sharpOCT, 0));
    }
    setProgress(20);
    //open balck space found, complete contour to left of fovea
    contour.add(
            findContourLeft(startPoint, Cardinality.SOUTH, startPoint, Cardinality.SOUTH, contour, sharpOCT));
    analysisManager.getImgPanel().setDrawPoint(new Point(foveaCenterXPosition, searchY));
    setProgress(30);
    /*
     since the contour can snake around due to aberations and low image density 
     we need to create a single line (represented by points) from left to right
     to represent the countour. This is easily done by building a line of
     points consisting of the point with the largest Y value (furthest from 
     the top of the image) at each X value. This eliminates overhangs from the 
     contour line.
     */
    Map<Double, List<Point>> grouped = contour.stream().collect(Collectors.groupingBy(Point::getX));
    List<Point> refinedEZContour = grouped.values().stream().map((List<Point> points) -> {
        int maxY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt();
        return new Point(points.get(0).x, maxY);
    }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList());
    setProgress(35);
    /*
     Starting from the identified location of the fovea search southward in 
     the image until the most southern pixels (in a 3x3 matrix of 
     pixels arround the the search point (X,Y) ) are black (ie. the search
     matrix has found that the search point isn't totally surrounded by
     white pixels). Then a recursive search algorithm determines if the 
     black area signifies the bottom of the Bruch's membrane or simply represents
     a closed (a black blob entirely surrounded by white pixels) black band.
     It will continue searching southward in the image until it can find an 
     open region of all black pixels. Once this is found it will find the contour
     of the edge between the black and white pixels, along the width of the image,
     of the bottom of the Bruch's membrane.
     */
    //        sharpOCT = getSharpenedOctImage(5D, 1.0F);
    searchY = (int) Math.round(brmInterp.value(foveaCenterXPosition));
    do {
        searchY++;
    } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
            || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
    contour = new LinkedList<>();
    startPoint = new Point(foveaCenterXPosition, searchY);
    /*
     Find contour by searching for white pixel boundary to te right of the fovea.
     Sometimes the crap below the Bruchs membrane causes too much interferance for the
     algorithm to work properly so we must tweak some of the parameters of the 
     sharpening performed on the image until the algorithm succedes or we can no longer
     tweak parameters. In the case of the later event we can use the raw segmented
     Bruchs membrane as a substitute to keep the method from failing.
     */
    contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
            sharpOCT, 0));
    double filtValue = 8.5D;
    boolean tweakFailed = false;
    while (contour.contains(null)) {
        contour = new LinkedList<>();
        filtValue -= 0.5D;
        System.out.println("Reducing sigma to " + filtValue);
        if (filtValue <= 0D) {
            tweakFailed = true;
            break;
        }
        sharpOCT = analysisManager.getSharpenedOctImage(8.5D, 1.0F);
        contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                sharpOCT, 0));
    }

    if (tweakFailed) {
        contour = new LinkedList<>(rawBrmPoints);
    } else {
        //search until open black area found (ie. if the search algorithm arrives back at
        //the starting pixel keep moving south to next black area to search)
        while (contour.get(0).equals(startPoint)) {
            contour = new LinkedList<>();
            do {
                searchY++;
            } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) == 0);
            do {
                searchY++;
            } while (Util.calculateGrayScaleValue(sharpOCT.getRGB(foveaCenterXPosition, searchY)) > 0
                    || isSurroundedByWhite(foveaCenterXPosition, searchY, sharpOCT));
            startPoint = new Point(foveaCenterXPosition, searchY);
            contour.add(findContourRight(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                    sharpOCT, 0));
        }
        setProgress(45);
        //open balck space found, complete contour to left of fovea
        contour.add(findContourLeft(startPoint, Cardinality.NORTH, startPoint, Cardinality.NORTH, contour,
                sharpOCT));
    }
    setProgress(55);
    /*
     since the contour can snake around due to aberations and low image density 
     we need to create a single line (represented by points) from left to right
     to represent the countour. This is easily done by building a line of
     points consisting of the point with the smallest Y value (closest to 
     the top of the image) at each X value. This eliminates overhangs from the 
     contour line.
     */
    grouped = contour.stream().collect(Collectors.groupingBy(Point::getX));
    List<Point> refinedBruchsMembraneContour = grouped.values().stream().map((List<Point> points) -> {
        int minY = points.stream().mapToInt((Point p) -> p.y).min().getAsInt();
        return new Point(points.get(0).x, minY);
    }).sorted((Point p1, Point p2) -> Integer.compare(p1.x, p2.x)).collect(Collectors.toList());
    setProgress(70);

    /*
     use a Loess interpolator again to smooth the new contours of the EZ and Bruch's Membrane
     */
    double[][] refinedContourPoints = Util.getXYArraysFromPoints(refinedEZContour);
    UnivariateFunction interpEZContour = interpolator.interpolate(refinedContourPoints[0],
            refinedContourPoints[1]);
    refinedContourPoints = Util.getXYArraysFromPoints(refinedBruchsMembraneContour);
    UnivariateFunction interpBruchsContour = interpolator.interpolate(refinedContourPoints[0],
            refinedContourPoints[1]);

    /*
     find the average difference in the distance in the Y between the 10 pixels
     at each end of the Bruch's Membrane contour and the contour created
     along the top of the EZ.
     */
    //since the lines are sorted on X position it is easy to align the lines
    //based on the tails of each line
    int minX = refinedEZContour.get(0).x;
    int maxX;
    //the interpolator can shorten the range of the X values from the original supplied
    //so we need to test where the end of the range occurs since it isn't directly accessible
    for (maxX = refinedEZContour.get(refinedEZContour.size() - 1).x; maxX > minX; maxX--) {
        try {
            double tmp = interpEZContour.value(maxX) - interpBruchsContour.value(maxX);
            //if this break is reached we have found the max value the interpolators will allow
            break;
        } catch (OutOfRangeException oe) {
            //do nothing but let loop continue
        }
    }
    double avgDif = Stream
            .concat(IntStream.range(minX + 30, minX + 50).boxed(),
                    IntStream.range(maxX - 49, maxX - 28).boxed())
            .mapToDouble(x -> interpBruchsContour.value(x) - interpEZContour.value(x)).average().getAsDouble();

    int height = sharpOCT.getHeight();//make to use in lambda expression
    List<LinePoint> ezLine = IntStream.rangeClosed(minX, maxX)
            .mapToObj(x -> new LinePoint(x, height - interpEZContour.value(x) - avgDif))
            .collect(Collectors.toList());
    List<LinePoint> bmLine = IntStream.rangeClosed(minX, maxX)
            .mapToObj(x -> new LinePoint(x, height - interpBruchsContour.value(x)))
            .collect(Collectors.toList());
    List<LinePoint> bmUnfiltLine = refinedBruchsMembraneContour.stream()
            .map((Point p) -> new LinePoint(p.x, height - p.getY())).collect(Collectors.toList());
    Util.graphPoints(ezLine, bmLine, bmUnfiltLine);
    analysisManager.getImgPanel().setDrawnLines(
            IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpEZContour.value(x)))
                    .collect(Collectors.toList()),
            IntStream.rangeClosed(minX, maxX).mapToObj(x -> new LinePoint(x, interpBruchsContour.value(x)))
                    .collect(Collectors.toList()));
    /*
     Find the difference between the two contours (Bruch's membrane and the
     EZ + Bruch's membrane) and use this to determine where the edge of the
     EZ is
     */
    List<LinePoint> diffLine = findDiffWithAdjustment(interpBruchsContour, 0D, interpEZContour, avgDif, minX,
            maxX);
    setProgress(90);
    //        List<LinePoint> peaks = Util.findPeaksAndVallies(diffLine);
    //        Util.graphPoints(diffLine, peaks);

    /*
     Find the first zero crossings of the difference line on both sides of the fovea.
     If a zero crossing can't be found then search for the first crossing of a
     value of 1, then 2, then 3, etc. until an X coordinate of a crossing is
     found on each side of the fovea.
     */
    OptionalInt ezLeftEdge;
    double crossingThreshold = 0.25D;
    do {
        double filtThresh = crossingThreshold;
        System.out.println("Crossing threshold = " + crossingThreshold);
        ezLeftEdge = diffLine.stream().filter(lp -> lp.getY() <= filtThresh && lp.getX() < foveaCenterXPosition)
                .mapToInt(LinePoint::getX).max();
        crossingThreshold += 0.25D;
    } while (!ezLeftEdge.isPresent());
    OptionalInt ezRightEdge;
    crossingThreshold = 0.25D;
    do {
        double filtThresh = crossingThreshold;
        System.out.println("Crossing threshold = " + crossingThreshold);
        ezRightEdge = diffLine.stream()
                .filter(lp -> lp.getY() <= filtThresh && lp.getX() > foveaCenterXPosition)
                .mapToInt(LinePoint::getX).min();
        crossingThreshold += 0.25D;
    } while (!ezRightEdge.isPresent());
    //return findings
    return new EZEdgeCoord(ezLeftEdge.getAsInt(), ezRightEdge.getAsInt());
}