Java 8:使用 Stream.of() 将逗号分隔的字符串转换为通用列表

huangapple go评论64阅读模式
英文:

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 = &quot;1,2,4,5&quot;;
List&lt;BigInteger&gt; lists = Stream.of(str.split(&quot;,&quot;)).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&lt;String, BigInteger&gt; 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&lt;String, T&gt;.

Given Function&lt;String, T&gt; converter, you can do:

List&lt;T&gt; items = Stream.of(str.split(&quot;,&quot;))
                      .map(String::trim)
                      .map(converter)
                      .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月22日 16:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64006308.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定