有没有办法为流的每个元素创建 2 个不同的对象并最后收集它们?
例如,如果我有 aList<String> stringList并且有一个GoddClass带有默认值和 a 的类customConstructor,我想在一个流中创建 2 个对象并最后收集
stringList
.stream()
.map(GoddClass::new)
.addAnothrObject(GoddClass::customConstructor) // Not a valid line, Just to depict what is needed
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
一个流可能不是实现我正在尝试的目标的正确解决方案。但这个问题留给专家们来解答。
我有三个 LocalDate(最后 3 天),对于每个日期,我想循环并执行一些操作:
StringBuilder result = "";
for (LocalDate currentDate = LocalDate.now(); currentDate.isAfter(LocalDate.now().minusDays(3)); currentDate = currentDate.minusDays(1)){
Page<User> users = userService.getAllUsersByRegistrationDate(currentDate);
String reportTable = reportService.getReportTable(users, tableTemplate);
result.append(reportTable);
}
Run Code Online (Sandbox Code Playgroud)
如何用 Stream API 替换此代码或提高可读性?
我有一个 spring 2.3.4.RELEASE 的休息端点当我使用 MockMvc 运行控制器测试时,我收到了
wsmsDefaultHandlerExceptionResolver :已解决[org.springframework.http.converter.HttpMessageNotWritableException:没有带有预设内容类型“application/json”的[class com.example.myexample.model.User]转换器]
@SpringBootTest(classes = UserController.class)
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
private static final String GET_USERBYID_URL = "/users/{userId}";
@Test
public void shouldGetUserWhenValid() throws Exception {
Address address = new Address();
address.setStreet("1 Abc St.");
address.setCity("Paris");
User userMock = new User();
userMock.setFirstname("Lary");
userMock.setLastname("Pat");
userMock.setAddress(address);
when(userRepository.findById(1)).thenReturn(Optional.of(userMock));
mockMvc.perform(get(GET_USERBYID_URL, "1").accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk());
}
}
@RestController
@RequestMapping(path = "/users")
@Slf4j
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping(value = "/{userId}", …Run Code Online (Sandbox Code Playgroud) 我想对以下结果使用可选:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。
我们应该怎么做 ?
我有一个对象:
class Sample
{
String currency;
String amount;
}
Run Code Online (Sandbox Code Playgroud)
我想要一个输出映射,其中包含特定货币的所有对象的总和。
例子-
指针。我一直在使用以下代码,但它没有按我的预期工作。您可以使用此代码作为参考:
Map<String, Double> finalResult = samples
.stream()
.collect(Collectors.toMap(
Sample::getCurrency,
e -> e.getAmount()
.stream()
.sum()));
Run Code Online (Sandbox Code Playgroud) 假设我们有一个包含字段的 person 类:
Class Person {
private String name;
private Integer id (this one is unique);
}
Run Code Online (Sandbox Code Playgroud)
然后我们有一个List<Person> people这样的:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Jerry', 112]
['Shannon', 259]
['Shannon', 533]
Run Code Online (Sandbox Code Playgroud)
我怎样才能创建一个新List<Person> uniqueNames的,使其仅过滤唯一名称并保留该名称的最高 ID。
所以最终列表将如下所示:
['Jerry', 993]
['Tom', 3]
['Neal', 443]
['Shannon', 533]
Run Code Online (Sandbox Code Playgroud) 我试图理解外部迭代器与内部迭代器之间的区别,其中外部迭代器使用迭代器来枚举其元素
List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
for(String letter: alphabets){
System.out.println(letter.toUpperCase());
}
Run Code Online (Sandbox Code Playgroud)
上面的后台代码做了类似下面的事情
List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
Iterator<String> iterator = alphabets.listIterator();
while(iterator.hasNext()){
System.out.println(iterator.next().toUpperCase());
}
Run Code Online (Sandbox Code Playgroud)
但对于内部迭代,一切都是在后台完成的,这对我来说是一个黑匣子,我想深入研究它。
就像下面的代码一样,迭代是在后台发生的,但到底发生了什么以及与 foreach 循环相比有何不同?
List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
alphabets.stream().forEach(l -> l.toUpperCase());
Run Code Online (Sandbox Code Playgroud)
这是我对外部迭代和内部迭代的理解。如果我错了,请纠正我。
我正在使用 IntelliJ 和OpenJDK 17创建 JavaFX 应用程序。项目语言级别设置为17。创建 JAR(构建工件)后,我尝试使用JRE 1.8.0_311执行它。当我这样做时,我收到此错误:
java.lang.UnsupportedClassVersionError: Main has been compiled by a more recent version of the Java Runtime (class file version 61.0), this version of the Java Runtime only recognizes class file versions up to 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
Error: A JNI error has occurred, please …Run Code Online (Sandbox Code Playgroud) Stream<Integer> stream = Stream.of(2, 1, 3, 4, 2, 3, 2);
Run Code Online (Sandbox Code Playgroud)
如果数字出现的次数较多,则显示该数字,结果为2
Stream<Integer> stream = Stream.of(2, 1, 3, 4, 2, 3);
Run Code Online (Sandbox Code Playgroud)
如果多个数字出现的次数相同,则取最大数字,结果为 2
Optional<Map.Entry<Integer, Long>> sorted1 = stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream().filter(k -> k.getValue() > 1).max(Comparator.comparing(Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)
我已经编写了上述逻辑,但无法获取这两个结果。
我有这门课:
\nclass Product {\n public double price;\n\n public Product(double price) {\n this.price = price;\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n还有一张地图:
\nMap<Product, Integer> products = new HashMap<>();\nRun Code Online (Sandbox Code Playgroud)\n其中包含添加的几种产品,如下所示:
\nproducts.put(new Product(2.99), 2);\nproducts.put(new Product(1.99), 4);\nRun Code Online (Sandbox Code Playgroud)\n我想使用流计算所有乘积的总和乘以值?我试过:
\ndouble total = products.entrySet().stream().mapToDouble((k, v) -> k.getKey().price * v.getValue()).sum();\nRun Code Online (Sandbox Code Playgroud)\n但它无法编译,我得到 \xe2\x80\x9c无法解析方法getValue()\xe2\x80\x9d。
我预计:
\n(2.99 * 2) + (1.99 * 4) = 5.98 + 7.96 = 13.94\nRun Code Online (Sandbox Code Playgroud)\n java ×10
java-8 ×10
java-stream ×6
collections ×2
collectors ×1
java-17 ×1
java-time ×1
javafx ×1
maxby ×1
option-type ×1
spring ×1
spring-boot ×1
spring-test ×1