Example usage for java.util Arrays binarySearch

List of usage examples for java.util Arrays binarySearch

Introduction

In this page you can find the example usage for java.util Arrays binarySearch.

Prototype

public static int binarySearch(Object[] a, Object key) 

Source Link

Document

Searches the specified array for the specified object using the binary search algorithm.

Usage

From source file:de.dhke.projects.cutil.collections.cow.CopyOnWriteMultiMapValueCollectionTest.java

/**
 * Test of iterator method, of class CopyOnWriteMultiMapValueCollection.
 *//*from  w w w.  ja v a  2s.  c om*/
@Test
public void testIterator() {
    Iterator<String> iter = _valueCollection.iterator();
    String[] referenceArray = { "a", "A", "b", "B", "c", "C" };
    Arrays.sort(referenceArray);
    for (int i = 0; i < _valueCollection.size(); ++i) {
        assertTrue(iter.hasNext());
        assertTrue(Arrays.binarySearch(referenceArray, iter.next()) >= 0);
    }
    assertFalse(iter.hasNext());

    _cowMap.copy();
    iter = _valueCollection.iterator();
    String first = iter.next();
    iter.remove();
    assertFalse(_cowMap.containsValue(first));
}

From source file:net.sf.taverna.t2.activities.wsdl.xmlsplitter.XMLSplitterConfigurationBeanBuilder.java

public static JsonNode buildBeanForInput(Element element) throws JDOMException, IOException {
    ObjectNode bean = JSON_NODE_FACTORY.objectNode();
    ArrayNode inputDefinitions = bean.arrayNode();
    bean.put("inputPorts", inputDefinitions);
    ArrayNode outputDefinitions = bean.arrayNode();
    bean.put("outputPorts", outputDefinitions);

    TypeDescriptor descriptor = XMLSplitterSerialisationHelper.extensionXMLToTypeDescriptor(element);
    ObjectNode outBean = outputDefinitions.addObject();
    outBean.put("name", "output");
    outBean.put("mimeType", "'text/xml'");
    outBean.put("depth", 0);
    outBean.put("granularDepth", 0);

    if (descriptor instanceof ComplexTypeDescriptor) {
        List<TypeDescriptor> elements = ((ComplexTypeDescriptor) descriptor).getElements();
        String[] names = new String[elements.size()];
        Class<?>[] types = new Class<?>[elements.size()];
        TypeDescriptor.retrieveSignature(elements, names, types);
        for (int i = 0; i < names.length; i++) {
            ObjectNode portBean = inputDefinitions.addObject();
            portBean.put("name", names[i]);
            portBean.put("mimeType", TypeDescriptor.translateJavaType(types[i]));
            portBean.put("depth", depthForDescriptor(elements.get(i)));
        }/*from w ww. j a  va 2  s .c o m*/

        List<TypeDescriptor> attributes = ((ComplexTypeDescriptor) descriptor).getAttributes();
        String[] elementNames = Arrays.copyOf(names, names.length);
        Arrays.sort(elementNames);
        String[] attributeNames = new String[attributes.size()];
        Class<?>[] attributeTypes = new Class<?>[attributes.size()];
        TypeDescriptor.retrieveSignature(attributes, attributeNames, attributeTypes);
        for (int i = 0; i < attributeNames.length; i++) {
            ObjectNode portBean = inputDefinitions.addObject();
            if (Arrays.binarySearch(elementNames, attributeNames[i]) < 0) {
                portBean.put("name", attributeNames[i]);
            } else {
                portBean.put("name", "1" + attributeNames[i]);
            }
            portBean.put("mimeType", TypeDescriptor.translateJavaType(attributeTypes[i]));
            portBean.put("depth", depthForDescriptor(attributes.get(i)));
        }

    } else if (descriptor instanceof ArrayTypeDescriptor) {
        ObjectNode portBean = inputDefinitions.addObject();
        portBean.put("name", descriptor.getName());

        if (((ArrayTypeDescriptor) descriptor).getElementType() instanceof BaseTypeDescriptor) {
            portBean.put("mimeType", "l('text/plain')");
        } else {
            portBean.put("mimeType", "l('text/xml')");
        }
        portBean.put("depth", 1);
    }

    String wrappedType = new XMLOutputter().outputString(element);
    bean.put("wrappedType", wrappedType);

    return bean;
}

From source file:de.dhke.projects.cutil.collections.cow.CopyOnWriteMultiMapKeySetTest.java

/**
 * Test of iterator method, of class CopyOnWriteMultiMapKeySet.
 *///from  w w w .j av a2s  .c  o  m
@Test
public void testIteratorCopyBefore() {
    Iterator<String> iter = _keySet.iterator();
    String[] referenceArray = { "1", "2", "3" };
    Arrays.sort(referenceArray);
    for (int i = 0; i < _keySet.size(); ++i) {
        assertTrue(iter.hasNext());
        assertTrue(Arrays.binarySearch(referenceArray, iter.next()) >= 0);
    }
    assertFalse(iter.hasNext());

    _cowMap.copy();
    iter = _keySet.iterator();
    String first = iter.next();
    iter.remove();
    assertFalse(_cowMap.containsKey(first));
}

From source file:org.apache.carbondata.scan.collector.impl.DictionaryBasedResultCollector.java

/**
 * This method will add a record both key and value to list object
 * it will keep track of how many record is processed, to handle limit scenario
 *///w w  w  . ja  v a  2s  . c  o m
@Override
public List<Object[]> collectData(AbstractScannedResult scannedResult, int batchSize) {

    List<Object[]> listBasedResult = new ArrayList<>(batchSize);
    boolean isMsrsPresent = measureDatatypes.length > 0;

    QueryDimension[] queryDimensions = tableBlockExecutionInfos.getQueryDimensions();
    List<Integer> dictionaryIndexes = new ArrayList<Integer>();
    for (int i = 0; i < queryDimensions.length; i++) {
        if (queryDimensions[i].getDimension().hasEncoding(Encoding.DICTIONARY)
                || queryDimensions[i].getDimension().hasEncoding(Encoding.DIRECT_DICTIONARY)) {
            dictionaryIndexes.add(queryDimensions[i].getDimension().getOrdinal());
        }
    }
    int[] primitive = ArrayUtils.toPrimitive(dictionaryIndexes.toArray(new Integer[dictionaryIndexes.size()]));
    Arrays.sort(primitive);
    int[] actualIndexInSurrogateKey = new int[dictionaryIndexes.size()];
    int index = 0;
    for (int i = 0; i < queryDimensions.length; i++) {
        if (queryDimensions[i].getDimension().hasEncoding(Encoding.DICTIONARY)
                || queryDimensions[i].getDimension().hasEncoding(Encoding.DIRECT_DICTIONARY)) {
            actualIndexInSurrogateKey[index++] = Arrays.binarySearch(primitive,
                    queryDimensions[i].getDimension().getOrdinal());
        }
    }

    QueryMeasure[] queryMeasures = tableBlockExecutionInfos.getQueryMeasures();
    Map<Integer, GenericQueryType> comlexDimensionInfoMap = tableBlockExecutionInfos
            .getComlexDimensionInfoMap();
    boolean[] dictionaryEncodingArray = CarbonUtil.getDictionaryEncodingArray(queryDimensions);
    boolean[] directDictionaryEncodingArray = CarbonUtil.getDirectDictionaryEncodingArray(queryDimensions);
    boolean[] complexDataTypeArray = CarbonUtil.getComplexDataTypeArray(queryDimensions);
    int dimSize = queryDimensions.length;
    boolean isDimensionsExist = dimSize > 0;
    int[] order = new int[dimSize + queryMeasures.length];
    for (int i = 0; i < dimSize; i++) {
        order[i] = queryDimensions[i].getQueryOrder();
    }
    for (int i = 0; i < queryMeasures.length; i++) {
        order[i + dimSize] = queryMeasures[i].getQueryOrder();
    }
    // scan the record and add to list
    int rowCounter = 0;
    int dictionaryColumnIndex = 0;
    int noDictionaryColumnIndex = 0;
    int complexTypeColumnIndex = 0;
    int[] surrogateResult;
    String[] noDictionaryKeys;
    byte[][] complexTypeKeyArray;
    while (scannedResult.hasNext() && rowCounter < batchSize) {
        Object[] row = new Object[dimSize + queryMeasures.length];
        if (isDimensionsExist) {
            surrogateResult = scannedResult.getDictionaryKeyIntegerArray();
            noDictionaryKeys = scannedResult.getNoDictionaryKeyStringArray();
            complexTypeKeyArray = scannedResult.getComplexTypeKeyArray();
            dictionaryColumnIndex = 0;
            noDictionaryColumnIndex = 0;
            complexTypeColumnIndex = 0;
            for (int i = 0; i < dimSize; i++) {
                if (!dictionaryEncodingArray[i]) {
                    row[order[i]] = DataTypeUtil.getDataBasedOnDataType(
                            noDictionaryKeys[noDictionaryColumnIndex++],
                            queryDimensions[i].getDimension().getDataType());
                } else if (directDictionaryEncodingArray[i]) {
                    DirectDictionaryGenerator directDictionaryGenerator = DirectDictionaryKeyGeneratorFactory
                            .getDirectDictionaryGenerator(queryDimensions[i].getDimension().getDataType());
                    if (directDictionaryGenerator != null) {
                        row[order[i]] = directDictionaryGenerator.getValueFromSurrogate(
                                surrogateResult[actualIndexInSurrogateKey[dictionaryColumnIndex++]]);
                    }
                } else if (complexDataTypeArray[i]) {
                    row[order[i]] = comlexDimensionInfoMap.get(queryDimensions[i].getDimension().getOrdinal())
                            .getDataBasedOnDataTypeFromSurrogates(
                                    ByteBuffer.wrap(complexTypeKeyArray[complexTypeColumnIndex++]));
                } else {
                    row[order[i]] = surrogateResult[actualIndexInSurrogateKey[dictionaryColumnIndex++]];
                }
            }

        } else {
            scannedResult.incrementCounter();
        }
        if (isMsrsPresent) {
            Object[] msrValues = new Object[measureDatatypes.length];
            fillMeasureData(msrValues, 0, scannedResult);
            for (int i = 0; i < msrValues.length; i++) {
                row[order[i + dimSize]] = msrValues[i];
            }
        }
        listBasedResult.add(row);
        rowCounter++;
    }
    return listBasedResult;
}

From source file:fr.landel.utils.assertor.helper.HelperMessage.java

/**
 * Converts parameters list into array and also converts types to improve
 * readability (ex: {@link Calendar} into {@link java.util.Date})
 * /*from   www  .  j a v a  2  s  . c o  m*/
 * @param parameters
 *            the input list
 * @return the output array
 */
public static Object[] convertParams(final List<ParameterAssertor<?>> parameters) {
    if (CollectionUtils.isNotEmpty(parameters)) {
        final List<Object> convertedParams = CollectionUtils2.transformIntoList(parameters,
                HelperAssertor.PARAM_TRANSFORMER);
        // The object, the type and if it's a checked object
        ParameterAssertor<?> param;
        int calendarField = -1;

        // in order for binary search
        final EnumType[] surroundable = new EnumType[] { EnumType.ARRAY, EnumType.ITERABLE, EnumType.MAP };

        for (int i = 0; i < parameters.size(); i++) {
            param = parameters.get(i);
            if (param.getObject() != null) {
                if (EnumType.DATE.equals(param.getType())
                        && Calendar.class.isAssignableFrom(param.getObject().getClass())) {
                    convertedParams.set(i, ((Calendar) param.getObject()).getTime());
                } else if (EnumType.CALENDAR_FIELD.equals(param.getType())) {
                    calendarField = (Integer) param.getObject();
                    if (CALENDAR_FIELDS.containsKey(calendarField)) {
                        convertedParams.set(i, CALENDAR_FIELDS.get(calendarField));
                    }
                } else if (EnumType.CLASS.equals(param.getType())) {
                    convertedParams.set(i, ((Class<?>) param.getObject()).getSimpleName());
                } else if (Arrays.binarySearch(surroundable, param.getType()) > -1) {
                    convertedParams.set(i,
                            HelperMessage.surroundByBrackets(param.getObject(), param.getType()));
                }
            }
        }
        return convertedParams.toArray();
    }
    return new Object[0];
}

From source file:com.github.xbn.text.CharUtil.java

/**
   <p>Get the (first) index at which a char exists in a char-array.</p>
        //www  . j  av  a  2s  .co  m
 * @param  to_find  The char to analyze.
 * @param  to_search  The array which {@code to_find} should be in. May not be null, and, if {@code do_orderAsc} is true, <i>should</i> be non-empty, unique, and sorted ascending. If not, this function will not work properly.
 * @param  do_orderAsc  If true, then <code>{@link java.util.Arrays}.{@link java.util.Arrays#binarySearch(char[], char) binarySearch}(c[],c)</code> is used to search the array. If false, a for loop is used.
 * @return  The first index in {@code to_search} at which {@code to_find} exists.
   <br/>{@code <b>-1</b>} If it doesn't.
 */
public static final int getFoundIdx(char to_find, char[] to_search, boolean do_orderAsc) {
    if (to_search == null) {
        throw new NullPointerException("to_search");
    }

    if (do_orderAsc) {
        return Arrays.binarySearch(to_search, to_find);
    }

    for (int i = 0; i < to_search.length; i++) {
        if (to_find == to_search[i]) {
            return i;
        }
    }

    return -1;
}

From source file:gedi.util.math.function.KnotFunction.java

public double integral(double from, double to) {
    int fi = Arrays.binarySearch(x, from);
    int ti = Arrays.binarySearch(x, to);

    double re = 0;
    if (-fi - 1 >= 0 && -fi - 1 < x.length) // if inside: linear interpolated value to 1
        re += noKnotBetweenintegral(from, x[-fi - 1]);

    if (-ti - 2 >= 0 && -ti - 2 < x.length) // if inside: 0 to linear interpolated value
        re += noKnotBetweenintegral(x[-ti - 2], to);

    if (fi < 0)
        fi = -fi - 1;/*ww  w  .j  a v a  2s .  com*/
    if (ti < 0)
        ti = -ti - 2;
    for (int k = fi; k < ti; k++)
        re += noKnotBetweenintegral(x[k], x[k + 1]);

    return re;
}

From source file:org.acegisecurity.acl.basic.AbstractBasicAclEntry.java

public int addPermissions(int[] permissionsToAdd) {
    if (logger.isDebugEnabled()) {
        logger.debug("BEFORE Permissions: " + printPermissionsBlock(mask) + " " + printBinary(mask) + " ("
                + mask + ")");
    }/*from   ww  w .j  a va 2  s  . co m*/

    for (int i = 0; i < permissionsToAdd.length; i++) {
        if (logger.isDebugEnabled()) {
            logger.debug("Add     permission: " + printPermissionsBlock(permissionsToAdd[i]) + " "
                    + printBinary(permissionsToAdd[i]) + " (" + permissionsToAdd[i] + ")");
        }

        this.mask |= permissionsToAdd[i];
    }

    if (Arrays.binarySearch(validPermissions, this.mask) < 0) {
        throw new IllegalArgumentException("Resulting permission set will be invalid.");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("AFTER  Permissions: " + printPermissionsBlock(mask) + " " + printBinary(mask) + " ("
                    + mask + ")");
        }

        return this.mask;
    }
}

From source file:ome.services.export.ExporterStepFactory.java

/**
 * Starts at the back of the provided path, looking for top-level objects.
 * If none is found, then a {@link GraphException} is thrown. Otherwise, the
 * length of the index array which should be passed to
 * {@link #id(String, int[])} is returned.
 *
 * @param path//from w w  w .  ja v  a 2 s .com
 * @return
 * @throws GraphException
 */
private int depth(String[] path) throws GraphException {
    for (int i = path.length - 1; i >= 0; i--) {
        String part = path[i];
        if (0 <= Arrays.binarySearch(TOP_LEVEL, part)) {
            return path.length - i; // length of search indexes needed
        }
    }
    throw new GraphException("Path without top-level:" + StringUtils.join(path));
}

From source file:net.sourceforge.pmd.lang.java.rule.errorprone.BeanMembersShouldSerializeRule.java

@Override
public Object visit(ASTClassOrInterfaceDeclaration node, Object data) {
    if (node.isInterface()) {
        return data;
    }//  w ww  .  j  av  a  2  s  .  com

    if (hasLombokAnnotation(node)) {
        return super.visit(node, data);
    }

    Map<MethodNameDeclaration, List<NameOccurrence>> methods = node.getScope()
            .getEnclosingScope(ClassScope.class).getMethodDeclarations();
    List<ASTMethodDeclarator> getSetMethList = new ArrayList<>(methods.size());
    for (MethodNameDeclaration d : methods.keySet()) {
        ASTMethodDeclarator mnd = d.getMethodNameDeclaratorNode();
        if (isBeanAccessor(mnd)) {
            getSetMethList.add(mnd);
        }
    }

    String[] methNameArray = imagesOf(getSetMethList);

    Arrays.sort(methNameArray);

    Map<VariableNameDeclaration, List<NameOccurrence>> vars = node.getScope()
            .getDeclarations(VariableNameDeclaration.class);
    for (Map.Entry<VariableNameDeclaration, List<NameOccurrence>> entry : vars.entrySet()) {
        VariableNameDeclaration decl = entry.getKey();
        AccessNode accessNodeParent = decl.getAccessNodeParent();
        if (entry.getValue().isEmpty() || accessNodeParent.isTransient() || accessNodeParent.isStatic()
                || hasIgnoredAnnotation((Annotatable) accessNodeParent)) {
            continue;
        }
        String varName = StringUtils.capitalize(trimIfPrefix(decl.getImage()));
        boolean hasGetMethod = Arrays.binarySearch(methNameArray, "get" + varName) >= 0
                || Arrays.binarySearch(methNameArray, "is" + varName) >= 0;
        boolean hasSetMethod = Arrays.binarySearch(methNameArray, "set" + varName) >= 0;
        // Note that a Setter method is not applicable to a final
        // variable...
        if (!hasGetMethod || !accessNodeParent.isFinal() && !hasSetMethod) {
            addViolation(data, decl.getNode(), decl.getImage());
        }
    }
    return super.visit(node, data);
}