Example usage for java.util Comparator Comparator

List of usage examples for java.util Comparator Comparator

Introduction

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

Prototype

Comparator

Source Link

Usage

From source file:TableRowColumnTest.java

public PlanetTableFrame() {
    setTitle("TableRowColumnTest");
    setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

    TableModel model = new DefaultTableModel(cells, columnNames) {
        public Class<?> getColumnClass(int c) {
            return cells[0][c].getClass();
        }/*from   ww  w . j av a  2s.  co m*/
    };

    table = new JTable(model);

    table.setRowHeight(100);
    table.getColumnModel().getColumn(COLOR_COLUMN).setMinWidth(250);
    table.getColumnModel().getColumn(IMAGE_COLUMN).setMinWidth(100);

    final TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
    table.setRowSorter(sorter);
    sorter.setComparator(COLOR_COLUMN, new Comparator<Color>() {
        public int compare(Color c1, Color c2) {
            int d = c1.getBlue() - c2.getBlue();
            if (d != 0)
                return d;
            d = c1.getGreen() - c2.getGreen();
            if (d != 0)
                return d;
            return c1.getRed() - c2.getRed();
        }
    });
    sorter.setSortable(IMAGE_COLUMN, false);
    add(new JScrollPane(table), BorderLayout.CENTER);

    removedRowIndices = new HashSet<Integer>();
    removedColumns = new ArrayList<TableColumn>();

    final RowFilter<TableModel, Integer> filter = new RowFilter<TableModel, Integer>() {
        public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
            return !removedRowIndices.contains(entry.getIdentifier());
        }
    };

    // create menu

    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu selectionMenu = new JMenu("Selection");
    menuBar.add(selectionMenu);

    rowsItem = new JCheckBoxMenuItem("Rows");
    columnsItem = new JCheckBoxMenuItem("Columns");
    cellsItem = new JCheckBoxMenuItem("Cells");

    rowsItem.setSelected(table.getRowSelectionAllowed());
    columnsItem.setSelected(table.getColumnSelectionAllowed());
    cellsItem.setSelected(table.getCellSelectionEnabled());

    rowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setRowSelectionAllowed(rowsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(rowsItem);

    columnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setColumnSelectionAllowed(columnsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(columnsItem);

    cellsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            table.clearSelection();
            table.setCellSelectionEnabled(cellsItem.isSelected());
            updateCheckboxMenuItems();
        }
    });
    selectionMenu.add(cellsItem);

    JMenu tableMenu = new JMenu("Edit");
    menuBar.add(tableMenu);

    JMenuItem hideColumnsItem = new JMenuItem("Hide Columns");
    hideColumnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedColumns();
            TableColumnModel columnModel = table.getColumnModel();

            // remove columns from view, starting at the last
            // index so that column numbers aren't affected

            for (int i = selected.length - 1; i >= 0; i--) {
                TableColumn column = columnModel.getColumn(selected[i]);
                table.removeColumn(column);

                // store removed columns for "show columns" command

                removedColumns.add(column);
            }
        }
    });
    tableMenu.add(hideColumnsItem);

    JMenuItem showColumnsItem = new JMenuItem("Show Columns");
    showColumnsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            // restore all removed columns
            for (TableColumn tc : removedColumns)
                table.addColumn(tc);
            removedColumns.clear();
        }
    });
    tableMenu.add(showColumnsItem);

    JMenuItem hideRowsItem = new JMenuItem("Hide Rows");
    hideRowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedRows();
            for (int i : selected)
                removedRowIndices.add(table.convertRowIndexToModel(i));
            sorter.setRowFilter(filter);
        }
    });
    tableMenu.add(hideRowsItem);

    JMenuItem showRowsItem = new JMenuItem("Show Rows");
    showRowsItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            removedRowIndices.clear();
            sorter.setRowFilter(filter);
        }
    });
    tableMenu.add(showRowsItem);

    JMenuItem printSelectionItem = new JMenuItem("Print Selection");
    printSelectionItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            int[] selected = table.getSelectedRows();
            System.out.println("Selected rows: " + Arrays.toString(selected));
            selected = table.getSelectedColumns();
            System.out.println("Selected columns: " + Arrays.toString(selected));
        }
    });
    tableMenu.add(printSelectionItem);
}

From source file:de.tudarmstadt.lt.n2n.utilities.PatternGenerator.java

public static int[][] comb(int k, int n, int[] fixed, boolean sort) {
    int[][] s = new int[0][];
    for (int u = 0; u < 1 << n; u++)
        if (bitcount(u) == k) {
            int[] c = bitadd(u, k);
            boolean add = true;
            for (int f : fixed)
                add &= !ArrayUtils.contains(c, f);
            if (add)
                s = (int[][]) ArrayUtils.add(s, c);
        }//from w w w  .  j  a  va  2 s. c  o m
    if (sort)
        Arrays.sort(s, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                for (int i = 0; i < o1.length; i++) {
                    int r = o2[i] - o1[i];
                    if (r != 0)
                        return r;
                }
                return 0;
            }
        });
    return s;
}

From source file:com.addthis.hydra.task.stream.TestStreamSourceMeshy.java

@Test
public void testStreamSourcesSort() {
    final StreamSourceMeshy source = new StreamSourceMeshy();
    final int numElements = 100000;

    FileReference[] fileRefs = new FileReference[numElements];
    List<MeshyStreamFile> streamFiles = new ArrayList<>(numElements);
    DateTime date = DateTime.now();/*from   w ww .  ja  va  2s.  c o  m*/

    try {
        for (int i = 0; i < numElements; i++) {
            fileRefs[i] = new FileReference("", 0, i);
            Field f = fileRefs[i].getClass().getDeclaredField("hostUUID");
            f.setAccessible(true);
            String uuid = RandomStringUtils.randomAlphabetic(20);
            f.set(fileRefs[i], uuid);
            streamFiles.add(new MeshyStreamFile(source, date, fileRefs[i]));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        fail();
    }

    Collections.shuffle(streamFiles);

    Collections.sort(streamFiles, new Comparator<MeshyStreamFile>() {
        @Override
        public int compare(MeshyStreamFile streamFile1, MeshyStreamFile streamFile2) {
            return source.compareStreamFiles(streamFile1, streamFile2);
        }
    });

}

From source file:net.sourceforge.jabm.evolution.FitnessProportionateBreeder.java

public double[] cummulativeFitnesses(AgentList agents) {
    agents.sortAgents(new Comparator<Agent>() {
        public int compare(Agent o1, Agent o2) {
            return new Double(getFitness(o1)).compareTo(new Double(getFitness(o2)));
        }//from   ww  w.  ja  v  a2s  .c  om
    });
    double[] result = new double[agents.size()];
    this.totalFitness = 0.0;
    for (int i = 0; i < result.length; i++) {
        totalFitness += getFitness(agents.get(i));
    }
    double cummulativeTotal = 0.0;
    for (int i = 0; i < result.length; i++) {
        double fitness = getFitness(agents.get(i));
        cummulativeTotal += fitness;
        result[i] = cummulativeTotal / totalFitness;
    }
    return result;
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.masterDegree.administrativeOffice.candidate.ReadExecutionDegreeByDegreeCurricularPlanID.java

protected InfoExecutionDegree run(String degreeCurricularPlanID, Integer executionDegreeIndex) {
    List infoExecutionDegreeList = null;
    Collection executionDegrees = null;

    DegreeCurricularPlan degreeCurricularPlan = FenixFramework.getDomainObject(degreeCurricularPlanID);

    executionDegrees = degreeCurricularPlan.getExecutionDegreesSet();

    infoExecutionDegreeList = new ArrayList();

    for (Iterator iter = executionDegrees.iterator(); iter.hasNext();) {
        ExecutionDegree executionDegree = (ExecutionDegree) iter.next();

        InfoExecutionDegree infoExecutionDegree = InfoExecutionDegree.newInfoFromDomain(executionDegree);
        infoExecutionDegreeList.add(infoExecutionDegree);
    }//from  ww w. j  a va2 s .c o  m

    Collections.sort(infoExecutionDegreeList, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            return ((InfoExecutionDegree) o2).getInfoExecutionYear().getBeginDate()
                    .compareTo(((InfoExecutionDegree) o1).getInfoExecutionYear().getBeginDate());
        }
    });

    return ((InfoExecutionDegree) infoExecutionDegreeList.get(executionDegreeIndex.intValue() - 1));
}

From source file:org.openmrs.module.kenyacore.CoreContext.java

/**
 * Refresh all content/*from   w  w w  . ja v  a  2 s .  c o m*/
 */
public synchronized void refresh() {
    refreshed = false;

    // Sort content managers by priority
    List<ContentManager> sorted = new ArrayList<ContentManager>(managers.values());
    Collections.sort(sorted, new Comparator<ContentManager>() {
        @Override
        public int compare(ContentManager cm1, ContentManager cm2) {
            return cm1.getPriority() - cm2.getPriority();
        }
    });

    log.info("Refreshing all content managers...");

    long start = System.currentTimeMillis();

    // Refresh each content manager
    for (ContentManager manager : sorted) {
        coreService.refreshManager(manager);
    }

    long time = System.currentTimeMillis() - start;

    log.info("Refreshed all content managers in " + time + "ms");

    refreshed = true;
}

From source file:com.aliyun.odps.ship.common.Util.java

public static File[] sortFiles(File[] fs) {

    if (fs == null) {
        return null;
    }/*  w ww. ja  va  2  s.  c  om*/
    //sort files
    List<File> files = Arrays.asList(fs);
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    return files.toArray(new File[files.size()]);
}

From source file:com.linkedin.pinot.core.startree.StarTreeDataTable.java

public void sort(int startRecordId, int endRecordId, final int startOffsetInRecord,
        final int endOffsetInRecord) {
    final MMapBuffer mappedByteBuffer;
    try {//from  www  .  j  a  v a  2  s .c  o  m
        int length = endRecordId - startRecordId;
        final long startOffset = startRecordId * (long) totalSizeInBytes;
        mappedByteBuffer = new MMapBuffer(file, startOffset, length * (long) totalSizeInBytes,
                MMapMode.READ_WRITE);

        List<Integer> idList = new ArrayList<Integer>();
        for (int i = startRecordId; i < endRecordId; i++) {
            idList.add(i - startRecordId);
        }
        Comparator<Integer> comparator = new Comparator<Integer>() {
            byte[] buf1 = new byte[dimensionSizeInBytes];
            byte[] buf2 = new byte[dimensionSizeInBytes];

            @Override
            public int compare(Integer o1, Integer o2) {
                long pos1 = (o1) * (long) totalSizeInBytes;
                long pos2 = (o2) * (long) totalSizeInBytes;

                //System.out.println("pos1="+ pos1 +" , pos2="+ pos2);
                mappedByteBuffer.toDirectByteBuffer(pos1, dimensionSizeInBytes).get(buf1);
                mappedByteBuffer.toDirectByteBuffer(pos2, dimensionSizeInBytes).get(buf2);
                IntBuffer bb1 = ByteBuffer.wrap(buf1).asIntBuffer();
                IntBuffer bb2 = ByteBuffer.wrap(buf2).asIntBuffer();
                for (int dimIndex : sortOrder) {
                    int v1 = bb1.get(dimIndex);
                    int v2 = bb2.get(dimIndex);
                    if (v1 != v2) {
                        return v1 - v2;
                    }
                }
                return 0;
            }
        };
        Collections.sort(idList, comparator);
        //System.out.println("AFter sorting:" + idList);
        int[] currentPositions = new int[length];
        int[] indexToRecordIdMapping = new int[length];
        byte[] buf1 = new byte[totalSizeInBytes];
        byte[] buf2 = new byte[totalSizeInBytes];

        for (int i = 0; i < length; i++) {
            currentPositions[i] = i;
            indexToRecordIdMapping[i] = i;
        }
        for (int i = 0; i < length; i++) {
            int thisRecordId = indexToRecordIdMapping[i];
            int thisRecordIdPos = currentPositions[thisRecordId];

            int thatRecordId = idList.get(i);
            int thatRecordIdPos = currentPositions[thatRecordId];

            //swap the buffers
            mappedByteBuffer.toDirectByteBuffer(thisRecordIdPos * (long) totalSizeInBytes, totalSizeInBytes)
                    .get(buf1);
            mappedByteBuffer.toDirectByteBuffer(thatRecordIdPos * (long) totalSizeInBytes, totalSizeInBytes)
                    .get(buf2);
            //        mappedByteBuffer.position(thisRecordIdPos * totalSizeInBytes);
            //        mappedByteBuffer.get(buf1);
            //        mappedByteBuffer.position(thatRecordIdPos * totalSizeInBytes);
            //        mappedByteBuffer.get(buf2);
            mappedByteBuffer.readFrom(buf2, 0, thisRecordIdPos * (long) totalSizeInBytes, totalSizeInBytes);
            mappedByteBuffer.readFrom(buf1, 0, thatRecordIdPos * (long) totalSizeInBytes, totalSizeInBytes);
            //        mappedByteBuffer.position(thisRecordIdPos * totalSizeInBytes);
            //        mappedByteBuffer.put(buf2);
            //        mappedByteBuffer.position(thatRecordIdPos * totalSizeInBytes);
            //        mappedByteBuffer.put(buf1);
            //update the positions
            indexToRecordIdMapping[i] = thatRecordId;
            indexToRecordIdMapping[thatRecordIdPos] = thisRecordId;

            currentPositions[thatRecordId] = i;
            currentPositions[thisRecordId] = thatRecordIdPos;
        }
        if (mappedByteBuffer != null) {
            mappedByteBuffer.flush();
            mappedByteBuffer.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        //      IOUtils.closeQuietly(randomAccessFile);
    }
}

From source file:springfox.documentation.spi.service.contexts.Orderings.java

public static Ordering<RequestHandler> byPatternsCondition() {
    return Ordering.from(new Comparator<RequestHandler>() {
        @Override/*from   ww w.  ja v a  2 s .  c o m*/
        public int compare(RequestHandler first, RequestHandler second) {
            return patternsCondition(first).toString().compareTo(patternsCondition(second).toString());
        }
    });
}

From source file:jp.co.tis.gsp.tools.dba.mojo.ExecuteDdlMojo.java

@Override
protected void executeMojoSpec() throws MojoExecutionException, MojoFailureException {
    DriverManagerUtil.registerDriver(driver);
    Dialect dialect = DialectFactory.getDialect(url);
    dialect.dropAll(user, password, adminUser, adminPassword, schema);
    dialect.createUser(user, password, adminUser, adminPassword);

    FilenameFilter sqlFileFilter = new FilenameFilter() {
        @Override//from w w  w.  j  av a  2s.c  o m
        public boolean accept(File dir, String name) {
            return name.endsWith(".sql");
        }
    };

    // ?.sql?
    List<File> files = new ArrayList<File>(Arrays.asList(ddlDirectory.listFiles(sqlFileFilter)));
    if (extraDdlDirectory != null && extraDdlDirectory.isDirectory()) {
        Collections.addAll(files, extraDdlDirectory.listFiles(sqlFileFilter));
    }

    // ?? ????
    Collections.sort(files, new Comparator<File>() {
        @Override
        public int compare(File f1, File f2) {
            return f1.getName().compareTo(f2.getName());
        }
    });
    try {
        executeBySqlFiles(files.toArray(new File[files.size()]));
    } catch (Exception e) {
        getLog().warn(e);
    }
}