Java Examples for java.util.Collections

The following java examples will help you to understand the usage of java.util.Collections. These source code samples are taken from different open source projects.

Example 1
Project: xbnjava-master  File: OrderIntListXmpl.java View source code
public static final void main(String[] ignored) {
    int[] aiNums = new int[] { 1, 11, 29, 12, 13, 19, 7, 2, 6, 16, 10, 15, 112, 18, 20, 3, 8, 5, 9, 14 };
    System.out.println("Unsorted: " + Arrays.toString(aiNums));
    ArrayList<Integer> alNums = new ArrayList<Integer>(aiNums.length);
    for (int i : aiNums) {
        alNums.add(i);
    }
    Collections.sort(alNums);
    System.out.println("Sorted: " + Arrays.toString(alNums.toArray()));
    int ixOf12 = Collections.<Integer>binarySearch(alNums, 12);
    System.out.println("Index of number 12: " + ixOf12);
}
Example 2
Project: ARTPart-master  File: Collections2Test.java View source code
/**
     * java.util.Collections#rotate(java.util.List, int)
     */
public void test_rotateLjava_util_ListI() {
    // Regression for HARMONY-19 Rotate an *empty* list
    Collections.rotate(new ArrayList<Object>(), 25);
    // Regression for HARMONY-20
    List<String> list = new ArrayList<String>();
    list.add(0, "zero");
    list.add(1, "one");
    list.add(2, "two");
    list.add(3, "three");
    list.add(4, "four");
    Collections.rotate(list, Integer.MIN_VALUE);
    assertEquals("Rotated incorrectly at position 0, ", "three", list.get(0));
    assertEquals("Rotated incorrectly at position 1, ", "four", list.get(1));
    assertEquals("Rotated incorrectly at position 2, ", "zero", list.get(2));
    assertEquals("Rotated incorrectly at position 3, ", "one", list.get(3));
    assertEquals("Rotated incorrectly at position 4, ", "two", list.get(4));
}
Example 3
Project: android-sdk-sources-for-api-level-23-master  File: Collections2Test.java View source code
/**
     * java.util.Collections#rotate(java.util.List, int)
     */
public void test_rotateLjava_util_ListI() {
    // Regression for HARMONY-19 Rotate an *empty* list
    Collections.rotate(new ArrayList<Object>(), 25);
    // Regression for HARMONY-20
    List<String> list = new ArrayList<String>();
    list.add(0, "zero");
    list.add(1, "one");
    list.add(2, "two");
    list.add(3, "three");
    list.add(4, "four");
    Collections.rotate(list, Integer.MIN_VALUE);
    assertEquals("Rotated incorrectly at position 0, ", "three", list.get(0));
    assertEquals("Rotated incorrectly at position 1, ", "four", list.get(1));
    assertEquals("Rotated incorrectly at position 2, ", "zero", list.get(2));
    assertEquals("Rotated incorrectly at position 3, ", "one", list.get(3));
    assertEquals("Rotated incorrectly at position 4, ", "two", list.get(4));
}
Example 4
Project: GlowstonePlusPlus-master  File: BlockPotato.java View source code
@Override
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
    if (block.getData() >= CropState.RIPE.ordinal()) {
        if (random.nextInt(100) < 2) {
            return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, random.nextInt(4) + 1), new ItemStack(Material.POISONOUS_POTATO, 1)));
        } else {
            return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, random.nextInt(4) + 1)));
        }
    } else {
        return Collections.unmodifiableList(Arrays.asList(new ItemStack(Material.POTATO_ITEM, 1)));
    }
}
Example 5
Project: nmonvisualizer-master  File: XMLParserHelper.java View source code
public static Map<String, String> parseAttributes(String unparsedAttributes) {
    if ((unparsedAttributes == null) || "".equals(unparsedAttributes)) {
        return java.util.Collections.emptyMap();
    }
    String[] parts = ATTRIBUTE_SPLIITTER.split(unparsedAttributes);
    int size = parts.length / 2;
    Map<String, String> attributes = new java.util.HashMap<String, String>(size);
    // drop odd numbered end index from array
    size *= 2;
    for (int i = 0; i < size; ) {
        attributes.put(DataHelper.newString(parts[i++].trim()), DataHelper.newString(parts[i++].trim()));
    }
    return attributes;
}
Example 6
Project: sonar-java-master  File: EnumSetCheck.java View source code
public void doSomething(Set<COLOR> param) {
    // compliant, we ignore parameters.
    // Noncompliant [[sc=23;ec=43]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> warm = new HashSet<COLOR>();
    Set foo = new HashSet();
    warm.add(COLORS.RED);
    warm.add(COLORS.ORANGE);
    SetString ss;
    SetColor sc;
    // Compliant, we check only initializer.
    ExtendedSet<COLOR> es;
    // Noncompliant [[sc=17;ec=37]] {{Convert this Set to an EnumSet.}}
    Set warm2 = new HashSet<COLOR>();
    EnumSet<COLOR> warm3 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<COLOR> warm4 = EnumSet.of(COLOR.RED, COLOR.ORANGE);
    Set<Integer> ports2 = new HashSet<>();
    // Noncompliant [[sc=24;ec=39]] {{Convert this Set to an EnumSet.}}
    Set<COLOR> ports = new HashSet<>();
    SetColor ports3 = new HashSet<>();
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports4 = Sets.immutableEnumSet(COLOR.RED);
    // Compliant - guava use an enum set with constraint of immutability
    Set<COLOR> ports5 = Sets.immutableEnumSet(Lists.newArrayList(COLOR.RED));
    Collection<COLOR> col = new ArrayList<>();
    Set<COLOR> col2 = java.util.Collections.unmodifiableSet(EnumSet.of(COLOR.RED, COLOR.ORANGE));
    // Noncompliant
    Set<COLOR> col3 = java.util.Collections.unmodifiableSet(new HashSet<COLOR>());
}
Example 7
Project: OSM2World-master  File: PowerModuleTest.java View source code
@Test
public void testRepeatedRendering() throws Exception {
    /* create fake data */
    List<OSMNode> nodes = asList(new OSMNode(0, 0, new MapBasedTagGroup(new Tag("power", "tower")), 101), new OSMNode(0, 0.001, new MapBasedTagGroup(new Tag("power", "tower")), 102));
    List<OSMWay> ways = asList(new OSMWay(new MapBasedTagGroup(new Tag("power", "line"), new Tag("cables", "4")), 201, nodes));
    OSMData osmData = new OSMData(EMPTY_LIST, nodes, ways, EMPTY_LIST);
    /* render to multiple targets */
    ConversionFacade cf = new ConversionFacade();
    StatisticsTarget t1 = new StatisticsTarget();
    StatisticsTarget t2 = new StatisticsTarget();
    List<Target<?>> targets = Arrays.<Target<?>>asList(t1, t2);
    List<WorldModule> modules = Collections.<WorldModule>singletonList(new PowerModule());
    cf.createRepresentations(osmData, modules, null, targets);
    for (Stat stat : Stat.values()) {
        assertEquals(t1.getGlobalCount(stat), t2.getGlobalCount(stat));
    }
}
Example 8
Project: j2objc-master  File: CollectionsTest.java View source code
/**
	 * @tests java.util.Collections#binarySearch(java.util.List,
	 *        java.lang.Object)
	 */
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // Test for method int
    // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
    // assumes ll is sorted and has no duplicate keys
    final int llSize = ll.size();
    // Ensure a NPE is thrown if the list is NULL
    try {
        Collections.binarySearch(null, new Object());
        fail("Expected NullPointerException for null list parameter");
    } catch (NullPointerException e) {
    }
    for (int counter = 0; counter < llSize; counter++) {
        assertEquals("Returned incorrect binary search item position", ll.get(counter), ll.get(Collections.binarySearch(ll, ll.get(counter))));
    }
}
Example 9
Project: android_platform_libcore-master  File: CollectionsTest.java View source code
/**
     * java.util.Collections#binarySearch(java.util.List,
     *        java.lang.Object)
     */
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // Test for method int
    // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
    // assumes ll is sorted and has no duplicate keys
    final int llSize = ll.size();
    // Ensure a NPE is thrown if the list is NULL
    try {
        Collections.binarySearch(null, new Object());
        fail("Expected NullPointerException for null list parameter");
    } catch (NullPointerException e) {
    }
    for (int counter = 0; counter < llSize; counter++) {
        assertTrue("Returned incorrect binary search item position", ll.get(Collections.binarySearch(ll, ll.get(counter))) == ll.get(counter));
    }
}
Example 10
Project: android-libcore64-master  File: CollectionsTest.java View source code
/**
     * java.util.Collections#binarySearch(java.util.List,
     *        java.lang.Object)
     */
public void test_binarySearchLjava_util_ListLjava_lang_Object() {
    // Test for method int
    // java.util.Collections.binarySearch(java.util.List, java.lang.Object)
    // assumes ll is sorted and has no duplicate keys
    final int llSize = ll.size();
    // Ensure a NPE is thrown if the list is NULL
    try {
        Collections.binarySearch(null, new Object());
        fail("Expected NullPointerException for null list parameter");
    } catch (NullPointerException e) {
    }
    for (int counter = 0; counter < llSize; counter++) {
        assertTrue("Returned incorrect binary search item position", ll.get(Collections.binarySearch(ll, ll.get(counter))) == ll.get(counter));
    }
}
Example 11
Project: open-mika-master  File: CollectionsTest.java View source code
/**
     * @tests java.util.Collections#binarySearch(java.util.List,
     *        java.lang.Object, java.util.Comparator)
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "binarySearch",
        args = {java.util.List.class, java.lang.Object.class, java.util.Comparator.class}
    )
     */
public void test_binarySearchLjava_util_ListLjava_lang_ObjectLjava_util_Comparator() {
    // Regression for HARMONY-94
    LinkedList<Integer> lst = new LinkedList<Integer>();
    lst.add(new Integer(30));
    Collections.sort(lst, null);
    int index = Collections.binarySearch(lst, new Integer(2), null);
    assertEquals(-1, index);
    LinkedList<String> lls = new LinkedList<String>();
    lls.add("1");
    lls.add("2");
    lls.add("3");
    lls.add("4");
    lls.add("");
    LinkedList<String> ll = lls;
    try {
        Collections.binarySearch(ll, new Integer(10), null);
        fail("ClassCastException expected");
    } catch (ClassCastException e) {
    }
}
Example 12
Project: org.openntf.domino-master  File: OperatorToObservableList.java View source code
@Override
public void onCompleted() {
    try {
        completed = true;
        /*
                     * Ideally this should just return Collections.unmodifiableList(list) and not copy it, 
                     * but, it ends up being a breaking change if we make that modification. 
                     * 
                     * Here is an example of is being done with these lists that breaks if we make it immutable:
                     * 
                     * Caused by: java.lang.UnsupportedOperationException
                     *     at java.util.Collections$UnmodifiableList$1.set(Collections.java:1244)
                     *     at java.util.Collections.sort(Collections.java:221)
                     *     ...
                     * Caused by: rx.exceptions.OnErrorThrowable$OnNextValue: OnError while emitting onNext value: UnmodifiableList.class
                     *     at rx.exceptions.OnErrorThrowable.addValueAsLastCause(OnErrorThrowable.java:98)
                     *     at rx.internal.operators.OperatorMap$1.onNext(OperatorMap.java:56)
                     *     ... 419 more
                     */
        o.onNext(new ArrayList<T>(list));
        o.onCompleted();
    } catch (Throwable e) {
        onError(e);
    }
}
Example 13
Project: molgenis-master  File: ScriptTest.java View source code
@Test
public void generateScript() throws IOException {
    FileStore fileStore = new FileStore(System.getProperty("java.io.tmpdir"));
    Map<String, Object> parameterValues = Collections.singletonMap("name", "Piet");
    Script script = mock(Script.class);
    when(script.getContent()).thenReturn("Hey ${name}");
    when(script.generateScript(fileStore, "txt", parameterValues)).thenCallRealMethod();
    File f = script.generateScript(fileStore, "txt", parameterValues);
    assertNotNull(f);
    assertTrue(f.exists());
    assertTrue(f.getPath().endsWith(".txt"));
    String s = FileCopyUtils.copyToString(new InputStreamReader(new FileInputStream(f)));
    assertEquals("Hey Piet", s);
    f.delete();
}
Example 14
Project: LambdaDojo-master  File: S201LambdaInsteadOfAnonClass.java View source code
// 2-1 Lambda 式で書きかえてみましょう
private void rewriteByLambda() {
    // この匿名クラスを Lambda 式で書きかえ
    Comparator<Integer> comparator = new Comparator<Integer>() {

        @Override
        public int compare(Integer x, Integer y) {
            return Integer.compare(x, y);
        }
    };
    List<Integer> numbers = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        numbers.add(i);
    }
    Random random = new Random();
    for (int i = 0; i < 10; i++) {
        Integer number = numbers.remove(random.nextInt(10 - i));
        numbers.add(number);
    }
    System.out.println("Before Sort: " + numbers);
    // 整数のリストをソート
    Collections.sort(numbers, comparator);
    System.out.println("After Sort: " + numbers);
}
Example 15
Project: liferay-ide-master  File: LiferayTomcatSourcePathComputer.java View source code
@Override
public ISourceContainer[] computeSourceContainers(ILaunchConfiguration configuration, IProgressMonitor monitor) throws CoreException {
    ISourceContainer[] superContainers = super.computeSourceContainers(configuration, monitor);
    // add theme plugin _diffs folders
    List<ISourceContainer> containers = new ArrayList<ISourceContainer>();
    //
    //        for( IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects() )
    //        {
    //            if( ProjectUtil.isThemeProject( project ) && ProjectUtil.isSDKProject( project ) )
    //            {
    //                IFolder diffs = project.getFolder( "docroot/_diffs" ); //$NON-NLS-1$
    //
    //                if( diffs.exists() )
    //                {
    //                    containers.add( new FolderSourceContainer( diffs, true ) );
    //                }
    //            }
    //            else if( "Servers".equals( project.getName() ) ) //$NON-NLS-1$
    //            {
    //                containers.add( new FolderSourceContainer( project, true ) );
    //            }
    //        }
    Collections.addAll(containers, superContainers);
    return containers.toArray(new ISourceContainer[0]);
}
Example 16
Project: dashboard-master  File: EventSumImpl.java View source code
@Override
public List<Event> getValue() {
    List<Event> ret = new ArrayList<Event>();
    DashboardRepository repository = WicketApplication.get().getRepository();
    for (Key curKey : repository.getKeys(Key.class)) {
        Collection<DataSource<?>> dataSources = repository.getData(curKey);
        for (DataSource<?> curDataSource : dataSources) {
            if (curDataSource instanceof EventSumImpl)
                continue;
            if (curDataSource instanceof Events) {
                List<Event> newEvents = ((Events) curDataSource).getValue();
                if (newEvents != null)
                    ret.addAll(newEvents);
            }
        }
    }
    Collections.sort(ret, new Comparator<Event>() {

        @Override
        public int compare(Event o1, Event o2) {
            return o1.getDateTime().compareTo(o2.getDateTime());
        }
    });
    return ret;
}
Example 17
Project: cloudtm-data-platform-master  File: ConverterClassAwareDmlCompiler.java View source code
public static void main(String[] args) throws Exception {
    final int c = args.length;
    final int offset = c - 3;
    final File dir = new File(args[offset]);
    final String[] baseArgs;
    if (dir.exists() && dir.isDirectory()) {
        final List<String> dmlFilenames = new ArrayList<String>();
        for (final File file : dir.listFiles()) {
            if (file.isFile() && file.getName().endsWith(".dml")) {
                dmlFilenames.add(file.getCanonicalPath());
            }
        }
        Collections.sort(dmlFilenames);
        List<URL> pluginDmlUrlList = PluginDmlUrlLoader.getPluginDmlUrlList();
        baseArgs = new String[c - 3 + dmlFilenames.size() + pluginDmlUrlList.size()];
        System.arraycopy(args, 0, baseArgs, 0, offset);
        int i = offset;
        for (URL pluginDmlUrl : pluginDmlUrlList) {
            baseArgs[i++] = pluginDmlUrl.toExternalForm();
        }
        for (final String dmlFilename : dmlFilenames) {
            baseArgs[i++] = dmlFilename;
        }
    } else {
        baseArgs = Arrays.copyOfRange(args, 0, c - 2);
    }
    DmlCompiler.main(baseArgs);
}
Example 18
Project: java8-tutorial-master  File: Lambda1.java View source code
public static void main(String[] args) {
    List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");
    Collections.sort(names, new Comparator<String>() {

        @Override
        public int compare(String a, String b) {
            return b.compareTo(a);
        }
    });
    Collections.sort(names, (String a, String b) -> {
        return b.compareTo(a);
    });
    Collections.sort(names, (String a, String b) -> b.compareTo(a));
    Collections.sort(names, ( a,  b) -> b.compareTo(a));
    System.out.println(names);
    names.sort(Collections.reverseOrder());
    System.out.println(names);
    List<String> names2 = Arrays.asList("peter", null, "anna", "mike", "xenia");
    names2.sort(Comparator.nullsLast(String::compareTo));
    System.out.println(names2);
    List<String> names3 = null;
    Optional.ofNullable(names3).ifPresent( list -> list.sort(Comparator.naturalOrder()));
    System.out.println(names3);
}
Example 19
Project: tapestry-model-master  File: DefaultExclusionsBMModifierTest.java View source code
@Test
void exclude() {
    BeanModel model = mockBeanModel();
    DescriptorService descriptorService = newMock(DescriptorService.class);
    TynamoClassDescriptorImpl classDescriptor = new TynamoClassDescriptorImpl(Foo.class);
    IdentifierDescriptor idProp = new IdentifierDescriptorImpl(Foo.class, "id", String.class);
    TynamoPropertyDescriptor multiWordProp = new TynamoPropertyDescriptorImpl(Foo.class, "multiWordProperty", String.class);
    CollectionDescriptor bazzesDescriptor = new CollectionDescriptor(Foo.class, "bazzes", Set.class);
    bazzesDescriptor.setElementType(Baz.class);
    Collections.addAll(classDescriptor.getPropertyDescriptors(), idProp, multiWordProp, bazzesDescriptor);
    expect(model.exclude("id", "bazzes")).andReturn(model);
    expect(model.getBeanType()).andReturn(Foo.class);
    expect(descriptorService.getClassDescriptor(Foo.class)).andReturn(classDescriptor);
    replay();
    DefaultExclusionsBMModifier modifier = new DefaultExclusionsBMModifier(descriptorService);
    modifier.modify(model, PageType.LIST.getContextKey());
    verify();
}
Example 20
Project: raylew_algorithm-master  File: 突击战.java View source code
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int m = scan.nextInt();
    ArrayList<Data> list = new ArrayList<Data>();
    for (int i = 0; i < m; i++) {
        int x = scan.nextInt();
        int y = scan.nextInt();
        Data d = new Data(x, y);
        list.add(d);
    }
    Collections.sort(list);
    int t1 = 0, t2 = 0;
    for (int i = 0; i < list.size(); i++) {
        Data d = list.get(i);
        if (i == 0) {
            t1 = d.x;
            t2 = d.y + t1;
            continue;
        }
        if (t1 + d.x + d.y < t2) {
            t1 += d.x;
        } else {
            t1 += d.x;
            t2 = d.y + t1;
        }
    }
    System.out.println(t2);
}
Example 21
Project: park-alert-master  File: UserRankServlet.java View source code
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String ranks = "";
    int total = 10;
    HashMap<Integer, String> tmp = new HashMap<Integer, String>();
    for (String user : Container.userRank.keySet()) {
        tmp.put(Container.userRank.get(user), user);
    }
    Collection<Integer> value = Container.userRank.values();
    ArrayList<Integer> ranksList = new ArrayList<Integer>(value);
    Collections.sort(ranksList);
    for (Integer rank : ranksList) {
        if (total == 0) {
            break;
        } else {
            total--;
            ranks = ranks + tmp.get(rank) + ";" + rank + ":";
        }
    }
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println(ranks);
}
Example 22
Project: korsakow-editor-master  File: MoveForwardsAction.java View source code
@Override
public void performAction() {
    WidgetCanvasModel model = interfBuilder.getCanvas().getModel();
    final List<WidgetModel> widgets = model.getWidgets();
    List<WidgetModel> selected = new ArrayList<WidgetModel>(model.getSelectedWidgets());
    Collections.sort(selected, new DepthSort(widgets));
    for (int i = selected.size() - 1; i >= 0; --i) {
        WidgetModel widget = selected.get(i);
        int index = model.indexOfWidget(widget);
        if (index + 2 > widgets.size())
            continue;
        if (index + 1 < widgets.size() && selected.contains(widgets.get(index + 1)))
            // preserve relative ordering
            continue;
        model.addWidget(index + 2, widget);
    }
}
Example 23
Project: sitebricks-master  File: FlatTemplateCompiler.java View source code
public Renderable compile(Class<?> page, Template template) {
    try {
        return registry.textWidget(template.getText(), new MvelEvaluatorCompiler(page));
    } catch (ExpressionCompileException e) {
        final List<CompileError> errors = Arrays.asList(CompileError.in(template.getText()).near(e.getError().getError().getLineNumber()).causedBy(e));
        final List<CompileError> warnings = Collections.emptyList();
        metrics.logErrorsAndWarnings(page, errors, warnings);
        throw new TemplateCompileException(page, template.getText(), errors, warnings);
    }
}
Example 24
Project: Desktop-master  File: RibbonTaskContributorFactory.java View source code
public void contribute(RibbonBuildContext context, ARibbonContributor parent) {
    hulls.clear();
    context.processChildren(context.getCurrentPath(), this);
    if (!hulls.isEmpty()) {
        Collections.sort(hulls, comparator);
        AbstractRibbonBand<?>[] bands = new AbstractRibbonBand<?>[hulls.size()];
        int count = 0;
        for (ComparableContributorHull<AbstractRibbonBand<?>> hull : hulls) {
            bands[count++] = hull.getObject();
        }
        RibbonTask task = new RibbonTask(TextUtils.removeTranslateComment(TextUtils.getText("ribbon." + getKey())), bands);
        if (parent != null) {
            parent.addChild(task, new ChildProperties(parseOrderSettings(attributes.getProperty("orderPriority", ""))));
        }
    }
}
Example 25
Project: many-ql-master  File: UIRadio.java View source code
@Override
public List<JRadioButton> applyStyles(List<JRadioButton> toComponent) {
    for (JRadioButton _radio : toComponent) {
        Font font = new Font(radio.getStyle().fontName(), Font.PLAIN, radio.getStyle().fontSize());
        Dimension dimension = new Dimension(radio.getStyle().width(), radio.getStyle().height());
        _radio.setPreferredSize(dimension);
        _radio.setSize(dimension);
        _radio.setForeground(radio.getStyle().color());
        _radio.setFont(font);
        Collections.replaceAll(toComponent, _radio, _radio);
    }
    return toComponent;
}