检查字符串对象中的数字是否在范围java 8之间



我想检查字符串中的数字是否在给定范围内。如果是,则将字符串中的数字加100,然后返回字符串。

例如,通道具有id名称和开始和结束时间

 // created list of channel object   
List<Channel> cList= Arrays.asList(
    new Channel(1,"BBC","0300","0500"),
    new Channel(2,"TR","0400","0509"),
    new Channel(3,"NEWS","0700","0800")); 
/*logic to identifyif the value is in between given rabge and add 100 to it.*/
List<Channel> cNewList=cList.forEach(
     // perform operation to find if c.getstartTime() between 
    // range(100,500).then add 100 in it.
);
               

我知道我们可以使用Integer.parseInt(String(方法转换为整数值,但我希望输出返回为字符串。

假设类Channel具有以下成员字段:

class Channel {
    private int index;
    private String name;
    private String startTime;
    private String endTime;
...
}

Main类中,您定义了一个静态辅助方法:

public class Main {
    private static Channel getNewStartTimeChannel(Channel c) {
        // parse the string to int
        int x = Integer.parseInt(c.getStartTime());
        if (x > 100 && x < 500) {
            return new Channel(
                    c.getIndex(),
                    c.getName(),
                    // update the int value of the startTime and transform it back to String
                    "" + (x + 100),
                    c.getEndTime());
        }
        return c;
    }

您可以很容易地将原始列表中的Channels转换为新的:

public static void main(String[] args) {
    List<Channel> cList = Arrays.asList(
            new Channel(1, "BBC", "0300", "0500"),
            new Channel(2, "TR", "0400", "0509"),
            new Channel(3, "NEWS", "0700", "0800")
    );
    List<Channel> cNewList = cList.stream()
                    .map(Main::getNewStartTimeChannel)
                    .collect(Collectors.toList());
}

必须将字符串解析为整数才能进行比较,因此您对parseInt很满意。

之后,您可以将整数与一个空字符串连接,以返回一个字符串(例如,1 + ""会给您一个字符串(。

最新更新