英文:
Java 8 : Comma separated string to Generic List using Stream.of()
问题
我需要一个通用的静态函数,用于将逗号分隔的字符串转换为通用列表。
String str = "1,2,4,5";
List<YourGenericType> lists = Stream.of(str.split(",")).map(String::trim).map(YourConversionFunction).collect(Collectors.toList());
取而代之的是这个 .map(YourConversionFunction),我需要一个通用的表达式来转换为通用列表。
英文:
I need a common static function for convert comma separated string to a generic list.
String str = "1,2,4,5";
List<BigInteger> lists = Stream.of(str.split(",")).map(String::trim).map(BigInteger::new).collect(Collectors.toList());
Instead of this .map(BigInteger::new) I need a generic expression to convert to generic list
答案1
得分: 4
BigInteger::new 步骤执行一个 Function<String, BigInteger>,将每个字符串转换为 BigInteger 的实例。如果您想对通用类型执行此操作,则需要一个将字符串转换为您的通用类型实例的函数。这意味着您需要一个 Function<String, T>。
给定 Function<String, T> converter,您可以执行以下操作:
List<T> items = Stream.of(str.split(","))
                      .map(String::trim)
                      .map(converter)
                      .collect(Collectors.toList());
英文:
The BigInteger::new step executes a Function<String, BigInteger> to convert each string to an instance of BigInteger. If you want to do this for a generic type, you need a function to convert a string to an instance of your generic type. That means you need a Function<String, T>.
Given Function<String, T> converter, you can do:
List<T> items = Stream.of(str.split(","))
                      .map(String::trim)
                      .map(converter)
                      .collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论