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:com.datatorrent.lib.multiwindow.SortedMovingWindowTest.java

/**
 * Given sorting key, sorting function, test sorting the map tuples within the sliding window
 */// www.  j a v  a 2 s.  c om
@Test
public void testSortingMapTupleWithoutKey() {

    SortedMovingWindow<Map<String, Integer>, Null> smw = new SortedMovingWindow<Map<String, Integer>, Null>();

    final String[] keys = { "number" };

    smw.setComparator(new Comparator<Map<String, Integer>>() {
        @Override
        public int compare(Map<String, Integer> o1, Map<String, Integer> o2) {
            // order the map by the value of key "number"
            return o1.get(keys[0]) - o2.get(keys[0]);
        }
    });
    CollectorTestSink<Object> testSink = new CollectorTestSink<Object>();
    smw.outputPort.setSink(testSink);
    smw.setup(null);
    smw.setWindowSize(2);

    // The incoming 6 simple map tuples are disordered among 4 windows
    emitObjects(smw,
            new Map[][] { createHashMapTuples(keys, new Integer[][] { { 1 }, { 3 } }),
                    createHashMapTuples(keys, new Integer[][] { { 2 }, { 5 } }),
                    createHashMapTuples(keys, new Integer[][] { { 4 } }),
                    createHashMapTuples(keys, new Integer[][] { { 6 } }) });
    smw.beginWindow(4);
    smw.endWindow();
    smw.beginWindow(5);
    smw.endWindow();

    // The outcome is ordered by the value of the key "number"
    Assert.assertEquals(
            Arrays.asList(
                    createHashMapTuples(keys, new Integer[][] { { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 } })),
            testSink.collectedTuples);
}

From source file:games.strategy.engine.random.PropertiesDiceRoller.java

/**
 * Loads the property dice rollers from the properties file
 * // w  w  w  .  j  av  a 2  s  .  c  om
 * @return the collection of available dice rollers
 */
public static Collection<PropertiesDiceRoller> loadFromFile() {
    final List<PropertiesDiceRoller> rollers = new ArrayList<PropertiesDiceRoller>();
    final File f = new File(GameRunner2.getRootFolder(), "dice_servers");
    if (!f.exists()) {
        throw new IllegalStateException("No dice server folder:" + f);
    }
    final java.util.List<Properties> propFiles = new ArrayList<Properties>();
    final File[] files = f.listFiles();
    for (final File file : files) {
        if (!file.isDirectory() && file.getName().endsWith(".properties")) {
            try {
                final Properties props = new Properties();
                final FileInputStream fin = new FileInputStream(file);
                try {
                    props.load(fin);
                    propFiles.add(props);
                } finally {
                    fin.close();
                }
            } catch (final IOException e) {
                System.out.println("error reading file:" + file);
                e.printStackTrace();
            }
        }
    }
    Collections.sort(propFiles, new Comparator<Properties>() {
        public int compare(final Properties o1, final Properties o2) {
            final int n1 = Integer.parseInt(o1.getProperty("order"));
            final int n2 = Integer.parseInt(o2.getProperty("order"));
            return n1 - n2;
        }
    });

    for (final Properties prop : propFiles) {
        rollers.add(new PropertiesDiceRoller(prop));
    }

    return rollers;
}

From source file:com.aionemu.gameserver.model.instance.instancereward.KamarBattlefieldReward.java

public List<KamarBattlefieldPlayerReward> sortPoints() {
    return sort(getInstanceRewards(), on(PvPArenaPlayerReward.class).getScorePoints(),
            new Comparator<Integer>() {
                @Override//from   www.  j  a v  a  2 s .c  o m
                public int compare(Integer o1, Integer o2) {
                    return o2 != null ? o2.compareTo(o1) : -o1.compareTo(o2);
                }
            });
}

From source file:org.web4thejob.web.panel.DefaultCommandsAuthorizationPanel.java

@Override
protected List<Command> getSourceList() {
    List<Command> commands = new ArrayList<Command>();
    for (CommandEnum id : CommandEnum.values()) {
        Command command = ContextUtil.getDefaultCommand(id, null);
        if (command != null) {
            commands.add(command);/*from w  w  w  .  j  a  v  a  2  s. co m*/
        }

        for (CommandEnum subid : id.getSubcommands()) {
            Subcommand subcommand = ContextUtil.getSubcommand(subid, command);
            if (subcommand != null) {
                commands.add(subcommand);
            }
        }
    }

    Collections.sort(commands, new Comparator<Command>() {
        @Override
        public int compare(Command o1, Command o2) {
            return o1.toString().compareToIgnoreCase(o2.toString());
        }
    });

    return commands;
}

From source file:com.jdom.word.playdough.android.AndroidGamePackResolver.java

@Override
public SortedSet<String> getGamePackNames() {
    InputStream openRawResource = null;
    String gamePackList = "";
    try {/*from  w w  w  . java2s  . co  m*/
        openRawResource = context.getResources().openRawResource(ID_OF_GAME_PACK_LIST);
        gamePackList = IOUtils.toString(openRawResource);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(openRawResource);
    }
    String[] gamePacks = StringUtils.split(gamePackList, '\n');

    TreeSet<String> treeSet = new TreeSet<String>(new Comparator<String>() {
        public int compare(String arg0, String arg1) {
            return new Integer(arg0).compareTo(new Integer(arg1));
        }
    });
    treeSet.addAll(Arrays.asList(gamePacks));
    return treeSet;
}

From source file:net.named_data.nfd.LogcatSettingsManager.java

private LogcatSettingsManager(Context context) {
    m_context = context;//from w  ww . j  ava2  s.c  o m
    m_logcatSettingItems = new ArrayList<>();
    m_logLevelMap = new HashMap<>();
    m_logcatTagsJSONSerializer = new LogcatTagsJSONSerializer(context, NFD_LOGCAT_TAGS_FILENAME);

    // Populate log level map
    loadLogLevelMap();

    // Check if previous tags setting exists; otherwise load defaults
    if (m_logcatTagsJSONSerializer.logcatTagsFileExists()) {
        loadSettingItems();
    } else {
        loadDefaultSettingItems();
    }

    // Save setting items to file
    saveSettingItems();

    // Sort log tag name lexicographically
    Collections.sort(m_logcatSettingItems, new Comparator<LogcatSettingItem>() {
        @Override
        public int compare(LogcatSettingItem lhs, LogcatSettingItem rhs) {
            return lhs.getLogTag().compareTo(rhs.getLogTag());
        }
    });
}

From source file:fll.web.playoff.Playoff.java

/**
 * Build the list of teams ordered from top to bottom (visually) of a single
 * elimination bracket.//from   ww  w . j  a  va  2  s  . co m
 * 
 * @param connection connection to the database
 * @param teams the teams in the playoffs
 * @return a List of teams
 * @throws SQLException on a database error
 */
public static List<Team> buildInitialBracketOrder(final Connection connection,
        final BracketSortType bracketSort, final WinnerType winnerCriteria, final List<? extends Team> teams)
        throws SQLException {
    if (null == connection) {
        throw new NullPointerException("Connection cannot be null");
    }

    final List<? extends Team> seedingOrder;
    if (BracketSortType.ALPHA_TEAM == bracketSort) {
        seedingOrder = teams;

        // sort by team name
        Collections.sort(seedingOrder, Team.TEAM_NAME_COMPARATOR);
    } else if (BracketSortType.RANDOM == bracketSort) {
        seedingOrder = teams;
        // assign a random number to each team
        final double[] randoms = new double[seedingOrder.size()];
        final Random generator = new Random();
        for (int i = 0; i < randoms.length; ++i) {
            randoms[i] = generator.nextDouble();
        }
        Collections.sort(seedingOrder, new Comparator<Team>() {
            public int compare(final Team one, final Team two) {
                final int oneIdx = seedingOrder.indexOf(one);
                final int twoIdx = seedingOrder.indexOf(two);
                return Double.compare(randoms[oneIdx], randoms[twoIdx]);
            }
        });
    } else {
        // standard seeding
        final int tournament = Queries.getCurrentTournament(connection);
        final int numSeedingRounds = TournamentParameters.getNumSeedingRounds(connection, tournament);
        if (numSeedingRounds < 1) {
            throw new FLLRuntimeException(
                    "Cannot initialize playoff brackets using scores from seeding rounds when the number of seeing rounds is less than 1");
        }

        seedingOrder = Queries.getPlayoffSeedingOrder(connection, winnerCriteria, teams);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("seedingOrder: " + seedingOrder);
    }

    final int[] seeding = computeInitialBrackets(seedingOrder.size());

    // give byes to the last byesNeeded teams.
    final List<Team> list = new LinkedList<Team>();
    for (final int element : seeding) {
        if (element > seedingOrder.size()) {
            list.add(Team.BYE);
        } else {
            final Team team = seedingOrder.get(element - 1);
            list.add(team);
        }
    }

    if (list.size() != seeding.length) {
        throw new InternalError("Programming error, list size should be the same as seeding length");
    }
    return list;

}

From source file:service.WorkReportService.java

private void sortDataList(List<WorkReportData> dataList) {
    Collections.sort(dataList, new Comparator<WorkReportData>() {

        @Override//from w  ww .  ja v a 2 s . co  m
        public int compare(WorkReportData o1, WorkReportData o2) {
            Date createDate1 = getDate(o1);
            Date createDate2 = getDate(o2);
            return -(createDate1.compareTo(createDate2));
        }

        private Date getDate(WorkReportData data) {
            if (data.getNotice() != null) {
                return data.getNotice().getNoticeDate();
            } else {
                return data.getLog().getCreateDate();
            }
        }

    });
}

From source file:de.hybris.platform.b2bacceleratorfacades.order.populators.ScheduledCartPopulator.java

/**
 * Returns the date of the first order placed chronologically.
 *///  w  ww.ja v  a2  s.c  om
protected Date getFirstOrderDate(final Collection<OrderModel> orders) {
    Date firstOrderDate = null;

    if (CollectionUtils.isNotEmpty(orders)) {
        final OrderModel firstOrder = Collections.min(orders, new Comparator<OrderModel>() {
            @Override
            public int compare(final OrderModel orderModel1, final OrderModel orderModel2) {
                return orderModel1.getDate().compareTo(orderModel2.getDate());
            }
        });
        firstOrderDate = firstOrder.getDate();
    }

    return firstOrderDate;
}

From source file:ch.digitalfondue.jfiveparse.TreeConstructionTest.java

@Parameters(name = "{0}:{index}:{2}")
public static List<Object[]> data() throws IOException {
    List<Object[]> data = new ArrayList<>();
    try (DirectoryStream<Path> ds = Files
            .newDirectoryStream(Paths.get("src/test/resources/html5lib-tests/tree-construction"), "*.dat")) {
        for (Path p : ds) {
            String file = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
            String[] testsAsString = file.split("\n\n#data\n");
            for (String t : testsAsString) {
                TreeConstruction treeTest = parse(t);
                if (treeTest.scriptingFlag == null) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else if (treeTest.scriptingFlag) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                }/*from  w ww . j av  a 2  s  . c o m*/
            }
        }
    }
    data.sort(new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new CompareToBuilder().append((String) o1[0], (String) o2[0])
                    .append((boolean) o1[2], (boolean) o2[2]).toComparison();
        }
    });
    return data;
}