我正在尝试使用stream()并放入地图来迭代列表,其中键是 steam 元素本身,值是 AtomicBoolean,true。
List<String> streamDetails = Arrays.asList("One","Two");
toReplay = streamDetails.stream().collect(Collectors.toMap(x -> x.toString(), new AtomicBoolean(true)));
Run Code Online (Sandbox Code Playgroud)
我在编译时收到以下错误。
Type mismatch: cannot convert from String to K
The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments ((<no type> x) -> {},
AtomicBoolean)
Run Code Online (Sandbox Code Playgroud)
我可能做错了什么,我应该用什么x -> x.toString()来代替?
在为项目做 mvn clean package 时,我遇到以下错误并且不明白错误的原因:
[ERROR] Failed to execute goal on project dbimport: Could not resolve dependencies for project
baag.betl:dbimport:jar:1.13-SNAPSHOT: Failure to find org.codehaus.groovy:groovy-all:jar:2.5.6 was cached in the local repository,
resolution will not be reattempted until the update interval of nexus has elapsed or updates are forced -> [Help 1]
Run Code Online (Sandbox Code Playgroud)
下面是我的 pom.xml 的一部分
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.5.6</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我在我的 Java 项目中使用 Intellij。
我正在尝试创建一个类似于 的自定义浮动添加Collectors.summingDouble()。
但我面临两个问题,我不知道如何解决它。
BiConsumer- 第 #27 行 - void 方法不能返回值Collectors.ofBiConsumer<R,T>- 第 32 行 - Collector 类型中的 (Supplier, , , Collector.Characteristics...)方法BinaryOperator<R>不适用于参数 ( Supplier<Float[]>, BiConsumer<Float,Employee>, BinaryOperator<Float>) 这里需要做什么来解决这个问题?public class CustomCollector {
public static void main(String[] args) {
Employee e1=new Employee(1,"Tom",10.2f);
Employee e2=new Employee(1,"Jack",10.4f);
Employee e3=new Employee(1,"Harry",10.4f);
ArrayList<Employee> lstEmployee=new ArrayList<Employee>();
lstEmployee.add(e1);lstEmployee.add(e2);lstEmployee.add(e3);
/* Implementation 1
* double totalSal=lstEmployee.stream().collect(Collectors.summingDouble(e->e.getSal()));
System.out.println(totalSal);
*/
//Implementation 2
Function<Employee,Float> fun=(e)->e.getSal();
BiConsumer<Float,Employee> consumer=(val,e)->val+e.getSal();
BinaryOperator<Float> operator=(val1,val2)->val1+val2;
Supplier<Float[]> supplier=() -> new Float[2]; …Run Code Online (Sandbox Code Playgroud) 我有以下方法将单行转换为地图
并想使用 java8 将其转换为单行语句
输入管道分隔的字符串,例如:status:MYSTATUS|data1:value1
public Map<String, String> getMap(String attributeUpdate){
Map<String, String> attr = new HashMap<>();
if(StringUtils.isNotEmpty(attributeUpdate)){
List<String> a = Arrays.asList(attributeUpdate.split("\\|"));
for (String s : a) {
String[] key_val = s.split(":");
if(key_val.length == 2) {
attr.put(key_val[0], key_val[1]);
}
}
}
return attr;
}
Run Code Online (Sandbox Code Playgroud) 我正在重构我的代码。我想在我的 DTO 中使用 java 记录而不是 java 类。要将 DTO 转换为实体,我使用的是 ModelMapper(2.3.5 版)。当我尝试获取有关用户的信息(调用方法将实体转换为 DTO)时,出现此错误。
Failed to instantiate instance of destination xxx.UserDto. Ensure that xxx.UserDto has a non-private no-argument constructor.
这是我的代码。
public record UserDto(String firstName,
String lastName,
String email,
String imageUrl) {}
Run Code Online (Sandbox Code Playgroud)
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired
private ModelMapper modelMapper;
@GetMapping("/user/me")
@PreAuthorize("hasRole('USER')")
public UserDto getCurrentUser(@CurrentUser UserPrincipal userPrincipal) {
return convertToDto(userRepository.findById(userPrincipal.getId())
.orElseThrow(() -> new ResourceNotFoundException("User", "id", userPrincipal.getId())));
}
private UserDto convertToDto(User user) {
UserDto userDto = modelMapper.map(user, UserDto.class);
return …Run Code Online (Sandbox Code Playgroud) 我有这个比较:
BigDecimal firstLimit = null; <<-------------------------sometimes firstLimit could be null
BigDecimal secondLimit = BigDecimal.valueof(10); <<--- sometimes secondLimit can be null
BigDecimal thirdLimit = BigDecimal.valueof(20); <<--- sometimes thirdLimit can be null
BigDecimal minLimit = firstLimit.min(secondLimit.min(thirLimit))
Run Code Online (Sandbox Code Playgroud)
最初,我尝试设置任何最终为空的值,并使用任意上限值,但我不允许这样做。这意味着我需要为冗长的 if-else-if 去掉这个单行比较解决方案,我真的不想这样做。是否有一种优雅的方法来处理空情况。任何建议将不胜感激。谢谢你。
我正在使用 Mysql GET_LOCK在分布式系统中实现锁定服务。在调用我的 getLock() 方法时,如果客户端获得了锁,我会在数据库中创建一个条目并在释放锁时删除该条目。
假设调用客户端将在达到其目的后释放锁。但是,我想确保在客户端不释放它或不进行适当清理的情况下释放锁。
一种方法是在我的锁定对象上使用 finalize 方法以在调用 finalize 时释放它。然而,它并不理想,增加了复杂性并且在 Java 9 中被弃用。我读到了比终结器更好的 Phantom 引用,但它的复杂程度也很高。我把它作为我的最后手段。
有没有更简单、更少依赖 JVM 的方法来处理这个用例?
java garbage-collection phantom-reference finalize finalizer
我知道匿名函数在 JS 中是如何工作的,并且对 Java 中的部分内容有点困惑。
所以在下面我有一个匿名类(我只是使用 Thread 类作为我所看到的示例),在那里我覆盖了run()函数,然后在该类上调用.start()。
new Thread() {
@Override
public void run() {
System.out.println("Hello from the anonymous class thread");
}
}.start();
Run Code Online (Sandbox Code Playgroud)
所以这是有效的,但 IntelliJ 想让我把它改写成这样:
new Thread(() -> System.out.println("Hello from the anonymous class thread")).start();
Run Code Online (Sandbox Code Playgroud)
我得到了大部分这种语法,但对如何覆盖run()函数有点困惑。根据我的理解,没有参数被传递到 Thread 类(所以没有任何参数被传递到我假设的构造函数中)。现在我感到困惑的地方就在这里。它没有在任何地方声明它覆盖了run()函数。这是Thread类的特例还是我遗漏了什么?
希望我清楚地解释了这一点,并提前致谢!
我很了解 Java,但是,前段时间使用过它。我遇到了一些新的东西,比如
打印。<String, String>toSysOut() .withLabel("source-stream")
Esp,突出显示部分,似乎 <String, String> 是 toSysOut() 的返回类型。大多数时候,我看到诸如
Printed.toSysOut().withLabel("source-stream")
什么样的表示法是,返回类型与引用运算符 (.)
我正在尝试根据 Java 列表中的重复来获取前 N 个值。
示例:查找前 2 个值
[“草莓”、“橙子”、“苹果”、“芒果”、“葡萄”、“菠萝”、“芒果”、“草莓”、“芒果”、“苹果”]
结果:
["mango"] //mango 重复了 3 次
["strawberries", "apple"] // "strawberries", "apple" 各重复了 2 次
我写了下面的代码来实现这一点
private static List<List<String>> getTop(int n, List<String> values) {
Map<String, Long> valueCountMap = values.stream()
.collect(groupingBy(x -> x, counting()));
final Map<String, Long> sortedByCount = valueCountMap.entrySet()
.stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
List<List<String>> topNValues = new ArrayList<>();
long prevValue = -1;
for (Map.Entry<String, Long> e : sortedByCount.entrySet()) {
if (prevValue == -1 || prevValue …Run Code Online (Sandbox Code Playgroud) java ×10
java-8 ×5
java-stream ×4
collections ×2
algorithm ×1
artifact ×1
bigdecimal ×1
collectors ×1
finalize ×1
finalizer ×1
generics ×1
java-14 ×1
java-record ×1
lambda ×1
maven ×1
modelmapper ×1
pom.xml ×1
sorting ×1