我有这个命令:
list.stream()
.filter(e -> ...)
.sorted(comparatorShuffle())
.findAny()
.orElse(null);
Run Code Online (Sandbox Code Playgroud)
这是comparatorShuffle():
public static <E> Comparator<E> comparatorShuffle(){
return new Comparator<>(){
private final List<Integer> temp = List.of(-1, 1);
private final Random random = new Random();
@Override
@SuppressWarnings("ComparatorMethodParameterNotUsed")
public int compare(E o1, E o2){
return temp.get(random.nextInt(temp.size()));
}
};
}
Run Code Online (Sandbox Code Playgroud)
有时我会遇到异常:IllegalArgumentException: Comparison method violates its general contract!
我明白为什么我得到这个,这是因为排序(它是随机的)不遵守规则:if A > B && B > C then A > C
有办法抑制/忽略这个错误吗?或者不使用的另一种方式来随机播放流collect?
我有一个像下面这样的课程,
public class Inventory {
private String name;
private List<Sample> samples;
}
public class Sample {
private int count;
private String date;
}
List<Inventory> inventories;
Run Code Online (Sandbox Code Playgroud)
我已经samples按日期排序了。没关系。但我需要按 Sample 类中的字段inventories对列表进行排序date。samples已经排序了。所以我需要库存按样品日期 DESC 排序。例如,
在该inventories列表中,如果有 3 个数据,
Inventory 1
name = 1
samples has dates of = List of (2021-07-02, 2021-07-03)
Inventory 2
name = 2
samples has dates of = List of (2021-07-02, 2021-09-03, 2021-10-03)
Inventory 3
name = 3
samples has dates …Run Code Online (Sandbox Code Playgroud) 我需要从列表中初始化映射的键,并为每个条目提供默认值。目前我使用 for 循环:
Map<String, String > myMap = new HashMap<>();
List<String> keys = Arrays.asList("a", "b", "c", "d");
for (String key : keys){
myMap.put(key, "default");
}
Run Code Online (Sandbox Code Playgroud)
有没有更干净的方法来做到这一点?也许是 Stream 或者 lambda ?
我有这样的集合:Map<Integer, List<MyObject>> collection
我想将整个列表映射MyObject到MyObjectDTO并返回带有映射列表的整个地图。
所以返回将是:
Map<Integer, List<MyObjectDto>> collectionWithDtos
最简单、最快的方法是什么?我已经检查了几种使用流的方法,但没有一个产生我预期的结果。谢谢
我有一个自然数列表。如何使用 Java Stream API 对所有可被 3、5 和两者整除的数字进行分组?
例如:
ArrayList<Integer> list = new ArrayList<>();
list.add(24);
list.add(25);
list.add(45);
list.add(30);
list.add(3);
list.add(20);
list.add(5);
Run Code Online (Sandbox Code Playgroud)
我想要 l3 = [3,24] ,l5 = [5,20,25],l35 = [45,30]
另外,我不想groupingBy()在名单上打电话三遍,因为名单真的很大。
我试图避免isPresent检查下面的代码,但编译器会发出错误消息
“不存在类型变量的实例,
U因此void符合U”
致电printAndThrowException. 这是我的代码:
values.stream()
.filter(value -> getDetails(value).getName.equals("TestVal"))
.findFirst()
.map(value -> printAndThrowException(value))
.orElseThrow(new Exception2("xyz"));
Run Code Online (Sandbox Code Playgroud)
所讨论的 printAndThrowException 方法具有以下签名:
void printAndThrowException(Pojo value)
Run Code Online (Sandbox Code Playgroud)
上面的方法总是抛出类型为 的异常RuntimeException。上述代码不是确切的代码,只是对我的代码进行了转换以代表情况。
这里有什么问题以及如何避免isPresent在调用时使用printAndThrowException?
我用来Files.walk()从目录中获取一些文件,但我从 Sonarqube 和 Sonarlint 代码分析中收到有关阻止程序错误的警告
连接、流、文件和其他实现 Closeable 接口或其超级接口 AutoCloseable 的类在使用后需要关闭。此外,该关闭调用必须在finally 块中进行,否则异常可能会导致调用无法进行。最好,当类实现 AutoCloseable 时,应使用“try-with-resources”模式创建资源并将自动关闭。
这是代码:
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
return ifRecordCollection;
Run Code Online (Sandbox Code Playgroud)
我读了这篇文章,几乎遇到了问题,但我不知道如何准确地将流停止在正确的位置。当我添加finally块时,它仍然给出相同的错误
try {
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
} finally {
Files.walk(Paths.get(ifRecordsPath)).close();
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
java spring try-catch-finally try-with-resources java-stream
我有一个简单的循环,可以将元素从一个添加list到另一个list。如何使用 来实现相同的结果streams?
List<User> users = new ArrayList<>();
for(User user: userRepository.findAll()) {
users.add(user);
}
Run Code Online (Sandbox Code Playgroud)
这样做的原因是因为
userRepository.findAll() 回报 Iterable<User>
我有一个Set<Person>,我需要过滤内容,然后填充给定集中的另一组。
我对流还很陌生。
我能想到的第一个解决方案是链接stream().filter().foreach()
解决方案一:
private Set<Person> mapPerson(final Set<Student> student) {
final Set<Person> person = new HashSet<>();
student.stream()
.filter(student1 -> Objects.nonNull(student.getAge()))
.forEach(student1 -> person.add(Person.builder()
.id(student1.getId())
.status(student1.getStatus()))
.build()));
return person;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定这是否可以通过链接来完成stream().filter().map()?
将不胜感激任何帮助,如果可以两种方式进行,哪种方式是首选方式?
有没有办法使用 Java Streams 来实现这一点?
List<String> list = new ArrayList<>();
list.add("x=aa,y=bb,y=cc");
list.add("y=dd,z=ee,w=ff");
list.add("w=gg,w=hh,w=ii");
Run Code Online (Sandbox Code Playgroud)
我想过滤上面的 ArrayList 以仅包含类型为“y”的字符串值。像下面这样
list=["bb","cc","dd"]
Run Code Online (Sandbox Code Playgroud)
我可以使用 String.split(",") 使用多行代码并将符合条件的子字符串插入到新的 ArrayList 中来实现此目的。但是有没有一种干净的方法可以使用 Java Streams 来实现这一点呢?
java ×10
java-stream ×10
collections ×2
hashmap ×1
iterable ×1
java-16 ×1
java-8 ×1
lambda ×1
option-type ×1
side-effects ×1
spring ×1