将String转换为java.util.Stream< Character> [英] Convert a String to a java.util.Stream<Character>

查看:236
本文介绍了将String转换为java.util.Stream< Character>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时我想对字符串中的每个字符做一些简单的事情。不幸的是,因为字符串是不可变的,除了循环遍历字符串之外没有好的方法可以做到这一点,这可能非常冗长。如果您使用Stream,则可以更短,只需一两行。

Sometimes I want to do something simple with each character in a string. Unfortunately, because a string is immutable, there is no good way of doing it except looping through the string which can be quite verbose. If you would use a Stream instead, it could be done much shorter, in just a line or two.

有没有办法转换字符串进入流<字符>

推荐答案

您可以使用 CharSequence 中提供的 chars()方法以及 String class实现了这个可以访问它的接口。
chars()方法返回 IntStream ,因此您需要将其强制转换为(char)如果您想将 IntStream 转换为 Stream< Character>

You can use chars() method provided in CharSequence and since String class implements this interface you can access it. The chars() method returns an IntStream , so you need to cast it to (char) if you will like to convert IntStream to Stream<Character>

例如

public class Foo {

    public static void main(String[] args) {
        String x = "new";

        Stream<Character> characters = x.chars().mapToObj(i -> (char) i);
        characters.forEach(System.out::println);
    }
}

这篇关于将String转换为java.util.Stream&lt; Character&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆