gpt4 book ai didi

java - Stream.of 具有混合输入内容

转载 作者:行者123 更新时间:2023-12-03 02:29:51 25 4
gpt4 key购买 nike

我想知道是否可以替换以下代码:

Object o;

// o can be one of the two following things
o = Arrays.asList("Toto", "tata", "Titi");
o = "Test";

if (o instanceof List<?>) {
((List<?>) o).stream().forEach(System.out::println);
} else {
System.out.println(o);
}

使用Stream.of来实现一些不那么丑陋的东西。我想到了这一点:

Object o;

// o can be one of the two following things
o = Arrays.asList("Toto", "tata", "Titi");
o = "Test";

Stream.of(o).forEach(System.out::println);

但显然它不起作用,因为 Stream.of(aList) 不会“展平”其内容。

有什么想法吗?我在梦想着不存在的东西吗?

谢谢

PS。我不知道 forEach 调用之前的 Object 类型。这些代码只是问题的一个简单示例。

最佳答案

如果您想要“不那么丑陋”的东西,您就不应该首先将数据类型扩展到Object:

List<String> o;

// o can be one of the two following things
o = Arrays.asList("Toto", "tata", "Titi");
o = Collections.singletonList("Test");

o.forEach(System.out::println);

当然,如果你有一个对象,你可以做类似的事情

(o instanceof List? ((List<?>)o).stream(): Stream.of(o)).forEach(System.out::println);

但我认为这仍然和你原来的方法一样丑陋......

关于java - Stream.of 具有混合输入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44258543/

25 4 0