按运行时参数对流进行排序
创始人
2024-08-23 07:30:12
0

以下是一个示例代码,演示如何按照运行时参数对流进行排序:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSortByRuntimeArgs {
    public static void main(String[] args) {
        List names = Arrays.asList("Alice", "Bob", "Charlie", "David");

        if (args.length > 0) {
            String sortType = args[0];
            switch (sortType) {
                case "asc":
                    sortNamesAscending(names);
                    break;
                case "desc":
                    sortNamesDescending(names);
                    break;
                default:
                    System.out.println("Invalid sort type. Please use 'asc' or 'desc'.");
            }
        } else {
            System.out.println("No sort type provided. Please provide 'asc' or 'desc' as runtime argument.");
        }
    }

    private static void sortNamesAscending(List names) {
        List sortedNames = names.stream()
                .sorted(Comparator.naturalOrder())
                .collect(Collectors.toList());
        System.out.println("Sorted names in ascending order: " + sortedNames);
    }

    private static void sortNamesDescending(List names) {
        List sortedNames = names.stream()
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());
        System.out.println("Sorted names in descending order: " + sortedNames);
    }
}

在该示例中,我们首先检查运行时参数是否提供了排序类型。如果提供了排序类型,我们使用 switch 语句根据参数值执行相应的排序方法。如果未提供排序类型,则打印一条相应的错误消息。

sortNamesAscending 方法使用 sorted 方法对流进行升序排序,并通过 collect 方法将排序结果收集到一个新的列表中。最后,打印排序后的结果。

sortNamesDescending 方法类似地使用 sorted 方法对流进行降序排序,并打印结果。

请注意,此示例假设运行时参数仅包含一个值,此值用于指定排序类型。如果需要处理多个参数或更复杂的逻辑,请相应地修改代码。

相关内容

热门资讯

推荐一款!hhpoker透视脚... 推荐一款!hhpoker透视脚本下载,wepoker有有规律,攻略教程(果真有挂)-哔哩哔哩1、实时...
科普!哈糖大菠萝有挂5个常用方... 科普!哈糖大菠萝有挂5个常用方法,卡农血拼辅助,透视教程(有挂透视)-哔哩哔哩1、下载好哈糖大菠萝有...
最新技巧!wepoker挂,泸... 最新技巧!wepoker挂,泸州大二新手攻略,微扑克教程(有挂方式)-哔哩哔哩1、泸州大二新手攻略系...
技术分享!wepoker科技辅... 技术分享!wepoker科技辅助器,邳州友友辅助app官网,分享教程(有挂教程)-哔哩哔哩在进入邳州...
分享一款!hhpoker为有挂... 分享一款!hhpoker为有挂一直输,决战卡五星开挂方法,扑克教程(有挂讲解)-哔哩哔哩运决战卡五星...
总算明白!wepoker免费脚... 总算明白!wepoker免费脚本咨询,微信小程序辅助器防检测,教你攻略(有挂方法)-哔哩哔哩1、用户...
我来向大家传授!wepoker... 我来向大家传授!wepoker辅助器安装包定制,同城上饶辅助,揭秘教程(有挂分享)-哔哩哔哩1、这是...
玩家必备科普!hhpoker必... 玩家必备科普!hhpoker必备开挂,hhpkoer辅助挂是真的,技巧教程(有挂工具)-哔哩哔哩1、...
记者爆料!wepoker轻量版... 记者爆料!wepoker轻量版有透视,欢乐联盟游戏辅助,介绍教程(了解有挂)-哔哩哔哩在进入wepo...
玩家实测!wpk私人局有透视,... 玩家实测!wpk私人局有透视,hhpoker德州机器人,揭秘教程(有挂透视)-哔哩哔哩在进入hhpo...