我有下面的代码,对于多次空检查有点难看.
String s = null;
if (str1 != null) {
s = str1;
} else if (str2 != null) {
s = str2;
} else if (str3 != null) {
s = str3;
} else {
s = str4;
}
Run Code Online (Sandbox Code Playgroud)
所以我尝试使用Optional.ofNullable如下所示,但如果有人读取我的代码仍然很难理解.在Java 8中这样做的最佳方法是什么.
String s = Optional.ofNullable(str1)
.orElse(Optional.ofNullable(str2)
.orElse(Optional.ofNullable(str3)
.orElse(str4)));
Run Code Online (Sandbox Code Playgroud)
在Java中9,我们可以使用Optional.ofNullable同OR,但在Java8还有没有其他办法?
有没有办法在一次处理中收集匹配和不匹配的流元素?举个例子:
final List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
final List<Integer> even = numbers.stream().filter( n -> n % 2 == 0 ).collect( Collectors.toList() );
final List<Integer> odd = numbers.stream().filter( n -> n % 2 != 0 ).collect( Collectors.toList() );
Run Code Online (Sandbox Code Playgroud)
有没有办法避免两次运行数字列表?像"比赛的收藏家和没有比赛的收藏家"这样的东西?
我正在尝试从员工列表中检索薪水最低的列表。到目前为止,我设法找到了薪水最低的员工,但是如果几个员工的薪水相同,我想检索多个员工。
我认为解决方案应该是一成不变的。因此,我无法创建一个薪水最低的变量,而只能检查每个薪水是否小于或等于Low_Salary。我尝试了一下,它奏效了。
因此,我相信我的问题是“ .min(比较器)”仅检索最低的一个。
Comparator<Employee> comparator = Comparator.comparing( Employee :: getSalary);
List<Employee> lowSalary = employees.stream()
.min(comparator)
.stream()
.collect(Collectors.toList());
lowSalary.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud) 我正在计算电子选举的选票,并且在我的初始版本中我只有一个政党。每个选民将有不同的线程,线程将更新给定政党的选票计数。
我决定使用 ConcurrentHashMap,但结果不是我所期望的......
Map<String, Integer> voting = new ConcurrentHashMap<>();
for (int i = 0; i < 16; i++) {
new Thread(() -> {
voting.put("GERB", voting.getOrDefault("GERB", 0) + 1);
}).start();
}
for (int i = 0; i < 100; i++) {
voting.put("GERB", voting.getOrDefault("GERB", 0) + 1);
}
Thread.sleep(5000); // Waits for the threads to finish
for (String s : voting.keySet()) {
System.out.println(s + ": " + voting.get(s));
}
Run Code Online (Sandbox Code Playgroud)
结果每次都不一样——范围从 114 到 116。
ConcurrentHashMap 不应该同步吗?
我有下面的值与哈希值映射,在值中我已经日期为字符串数据类型。我想比较地图中所有可用的日期,并仅提取一个具有最近日期的键值。
我想与值而不是键进行比较。
我已包含以下代码
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("1", "1999-01-01");
map.put("2", "2013-10-11");
map.put("3", "2011-02-20");
map.put("4", "2014-09-09");
map.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));
}
}
Run Code Online (Sandbox Code Playgroud)
预期的输出是:
关键4值2014-09-09
我在"实践中的Java并发"第14.6.1节中阅读了有关ReentrantLock实现的一些细节,注释中的某些内容让我感到困惑:
因为受保护的状态操作方法具有易失性读取或写入的内存语义,并且ReentrantLock 只有在调用getState之后才会读取所有者字段并且仅在调用setState之前写入它,ReentrantLock可以依赖于同步状态的内存语义,因此避免进一步同步见第16.1.4节.
它引用的代码:
protected boolean tryAcquire(int ignored) {
final Thread current = Thread.currentThread();
int c = getState();
if (c ==0) {
if (compareAndSetState(0, 1)) {
owner = current;
return true;
}
} else if (current == owner) {
setState(c+1);
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
我相信这是对简化代码nonfairTryAcquire的ReentrantLock.Sync.
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true; …Run Code Online (Sandbox Code Playgroud) java concurrency multithreading synchronization memory-barriers
我有一个包含字符串列表的模型类.列表可以为空或包含元素.如果它有元素,那么这些元素不能为空.举个例子,假设我有一个叫做QuestionPaper的类,它有一个questionIds列表,每个都是一个字符串.
class QuestionPaper{
private List<String> questionIds;
....
}
Run Code Online (Sandbox Code Playgroud)
论文可以有零个或多个问题.但如果有问题,则id值不能为空字符串.我正在使用SpringBoot,Hibernate,JPA和Java编写一个微服务.我该怎么做这个验证.任何帮助表示赞赏.
举个例子,我们需要拒绝来自用户的以下json输入.
{ "examId": 1, "questionIds": [ "", " ", "10103" ] }
Run Code Online (Sandbox Code Playgroud)
是否有任何开箱即用的方法来实现这一目标,或者我是否必须为此编写自定义验证器.
我有一个类型列表,List<A>并且通过map操作获得了List<B>所有A元素合并到一个列表中的类型的集合列表。
List<A> listofA = [A1, A2, A3, A4, A5, ...]
List<B> listofB = listofA.stream()
.map(a -> repo.getListofB(a))
.flatMap(Collection::stream)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
没有平面图
List<List<B>> listOflistofB = listofA.stream()
.map(a -> repo.getListofB(a))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我想将结果收集为类型图,Map<A, List<B>>到目前为止,我尝试使用各种Collectors.toMap或Collectors.groupingBy选项,但无法获得所需的结果。
我正在尝试订阅可观察对象,例如:
List<String> colors = Arrays.asList("RED", "BLACK", "WHITE", "GREEN", "YELLOW", "BROWN", "PURPUL", "BLUE");
Observable.just(colors).subscribe(s -> System.out.println(s));
Run Code Online (Sandbox Code Playgroud)
它工作正常,但如果我使用方法引用编译器会给出错误“void is not afunctional iterface”
谁能解释得有点深?根据我的说法,订阅者接受消费者功能接口,它不返回任何内容,但我们可以打印流数据,例如:
Observable.just(colors).subscribe(s -> System.out::println);// NOT COMPILE
Run Code Online (Sandbox Code Playgroud) Map<Integer, String> map = new HashMap<>();
map.put(1, "f");
map.put(2, "i");
map.put(3, "a");
map.put(4, "c");....etc
Run Code Online (Sandbox Code Playgroud)
现在我有一个列表:
List<Integer> picks = {1,3}
Run Code Online (Sandbox Code Playgroud)
我想取回一个字符串列表,即映射中与“ pick”列表中找到的键值匹配的值。因此,我希望取回{“ f”,“ a”}作为结果。有没有一种方法可以使用Java流api优雅地做到这一点?
当有一个值时,我就是这样:
map.entrySet().stream()
.filter(entry -> "a".equals(entry.getValue()))
.map(entry -> entry.getValue())
.collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)
但是,当要过滤的键/小贴士列表变得越来越困难时。
java ×10
java-8 ×9
java-stream ×6
lambda ×6
collectors ×2
concurrency ×2
date ×1
hashmap ×1
optional ×1
rx-java2 ×1
spring ×1
validation ×1