标签: java-8

为 Java 流的每个元素创建 2 个对象

有没有办法为流的每个元素创建 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)

一个流可能不是实现我正在尝试的目标的正确解决方案。但这个问题留给专家们来解答。

java java-8 java-stream collectors

0
推荐指数
1
解决办法
1057
查看次数

使用 Stream API 迭代 LocalDate

我有三个 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 替换此代码或提高可读性?

java java-8 java-stream java-time

0
推荐指数
1
解决办法
761
查看次数

MockMvc 使用 application/json 返回 HttpMessageNotWritableException

我有一个 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)

java spring spring-test java-8 spring-boot

0
推荐指数
1
解决办法
2345
查看次数

可选,测试值是否不为空且不为空

我想对以下结果使用可选:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。

我们应该怎么做 ?

java java-8 option-type

0
推荐指数
1
解决办法
2235
查看次数

如何创建包含所有特定对象总和的地图?

我有一个对象:

class Sample
{
    String currency;
    String amount;
}
Run Code Online (Sandbox Code Playgroud)

我想要一个输出映射,其中包含特定货币的所有对象的总和。

例子-

  • 40 印度卢比
  • 80 美元
  • 20 欧元

指针。我一直在使用以下代码,但它没有按我的预期工作。您可以使用此代码作为参考:

Map<String, Double> finalResult = samples
        .stream()
        .collect(Collectors.toMap(
                Sample::getCurrency,
                e -> e.getAmount()
                      .stream()
                      .sum()));
Run Code Online (Sandbox Code Playgroud)

java collections java-8 java-stream

0
推荐指数
1
解决办法
420
查看次数

Java 8按唯一名称过滤对象列表,同时仅保留最高ID?

假设我们有一个包含字段的 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)

java collections java-8 maxby java-stream

0
推荐指数
1
解决办法
2232
查看次数

java 8 流的内部迭代是什么样子的

我试图理解外部迭代器与内部迭代器之间的区别,其中外部迭代器使用迭代器来枚举其元素

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)

这是我对外部迭代和内部迭代的理解。如果我错了,请纠正我。

java java-8 java-stream

0
推荐指数
1
解决办法
570
查看次数

无法运行使用 Java 17 编译的 JRE 1.8_311 的 JAR

我正在使用 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)

java javafx java-8 java-17

0
推荐指数
1
解决办法
2万
查看次数

使用stream api获取最大数量

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)

我已经编写了上述逻辑,但无法获取这两个结果。

java java-8

0
推荐指数
1
解决办法
186
查看次数

如何在Java中将Map中的key * value相乘?

我有这门课:

\n
class Product {\n    public double price;\n\n    public Product(double price) {\n        this.price = price;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

还有一张地图:

\n
Map<Product, Integer> products = new HashMap<>();\n
Run Code Online (Sandbox Code Playgroud)\n

其中包含添加的几种产品,如下所示:

\n
products.put(new Product(2.99), 2);\nproducts.put(new Product(1.99), 4);\n
Run Code Online (Sandbox Code Playgroud)\n

我想使用流计算所有乘积的总和乘以值?我试过:

\n
double total = products.entrySet().stream().mapToDouble((k, v) -> k.getKey().price * v.getValue()).sum();\n
Run Code Online (Sandbox Code Playgroud)\n

但它无法编译,我得到 \xe2\x80\x9c无法解析方法getValue()\xe2\x80\x9d。

\n

我预计:

\n
(2.99 * 2) + (1.99 * 4) = 5.98 + 7.96 = 13.94\n
Run Code Online (Sandbox Code Playgroud)\n

java java-8 java-stream

0
推荐指数
1
解决办法
895
查看次数