Kja*_*ara -2 c# java iterable enumerable
在 C# 中,我可以将单个元素转换为IEnumerable<>
如下所示(此处使用扩展方法):
static class Extensions
{
static IEnumerable<T> Yield<T>(this T t)
{
yield return t;
}
}
Run Code Online (Sandbox Code Playgroud)
当我需要在IEnumerable<>
某处输入但只有一个元素时,我会使用它,如下所示:
var myList = new List<string>("foo".Yield());
Run Code Online (Sandbox Code Playgroud)
在 Java 中是否有一些等效的方法可以做到这一点?
Iterable<>
我对从像这样的元素实际创建堆上不感兴趣
List<String> myIterable = new ArrayList<String>();
myIterable.add("foo");
Run Code Online (Sandbox Code Playgroud)
因为我已经知道那种解决方案;我想知道 Java 是否可以像 C# 一样强大且惰性地处理可枚举/可迭代(C# 有 Linq 和 Yield Return,Java 有 Streams)。
最简单的方法是使用Collections.singleton()
or Collections.singletonList()
。
Collections.singleton(1);
Collections.singletonList("");
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,返回的集合都是不可变的,它们仅由实际元素支持。从某种意义上说,它们不是真正的集合,因为它们只允许迭代和其他非修改操作。
或者您可以自己实现Iterator
和Iterable
,尽管这会在某种程度上重新实现上述内容(jdk 已经提供了类似/相同的功能)。
public class SingleElementIterator<T> implements Iterator<T> {
private final T element;
private boolean hasNext;
public SingleElementIterator(T element) {
this.element = element;
this.hasNext = true;
}
@Override
public boolean hasNext() {
return this.hasNext;
}
@Override
public T next() {
if (this.hasNext) {
this.hasNext = false;
return this.element;
}
throw new NoSuchElementException();
}
}
Run Code Online (Sandbox Code Playgroud)
public class SingleElementIterable<T> implements Iterable<T> {
private final T element;
public SingleElementIterable(T element) {
this.element = element;
}
@Override
public Iterator<T> iterator() {
return new SingleElementIterator<>(this.element);
}
}
Run Code Online (Sandbox Code Playgroud)
例子:
public class Temp {
public static void main(String[] args) {
Iterable<String> iterable = new SingleElementIterable<>("abc");
for (String string : iterable) {
System.out.println(string);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
458 次 |
最近记录: |