当我从地图中检索地图条目时,将其存储在一个可选中,然后使用 remove(entry.getKey()) 从地图中删除相同的条目,然后Optional突然开始指向地图内可用的下一个地图条目。
让我进一步解释:
我有一堆我想排序的评论对象。评论列表应始终以被接受为答案的评论开头,它应该是列表中的第一个元素。sort 方法以映射开始,并使用 entrySet 上的流来检索acceptedAnswer布尔值设置为的第一个注释true。
Map<Long, CommentDTO> sortedAndLinkedCommentDTOMap = sortCommentsAndLinkCommentRepliesWithOwningComments(commentDTOSet);
Optional<Map.Entry<Long, CommentDTO>> acceptedAnswerCommentOptional = sortedAndLinkedCommentDTOMap.entrySet().stream()
.filter(entry -> entry.getValue().isAcceptedAsAnswer()).findFirst();
Run Code Online (Sandbox Code Playgroud)
让我们假设Map包含 3 个带有 ids 的评论3, 6, and 11。键始终是评论的 id,评论始终是值。标记为答案的评论具有 id 6。在这种情况下,将执行以下代码:
if(acceptedAnswerCommentOptional.isPresent()){
Map.Entry<Long, CommentDTO> commentDTOEntry = acceptedAnswerCommentOptional.get();
sortedAndLinkedCommentDTOMap.remove(commentDTOEntry.getKey());
}
Run Code Online (Sandbox Code Playgroud)
当commentDTOEntry使用acceptedAnswerCommentOptional它的值初始化时,它引用了 id 为 6 的已接受答案。现在,当我从sortedAndLinkedCommentDTOMap对已接受答案的引用中删除该条目时,注释不仅sortedAndLinkedCommentDTOMap从acceptedAnswerCommentOptional! 但是acceptedAnswerCommentOptional现在开始指向下一个条目,sortedAndLinkedCommentDTOMap即带有key 11.
我不明白是什么导致了这种奇怪的行为。为什么acceptedAnswerCommentOptional不简单地成为价值null?acceptedAnswerCommentOptional …
我需要查找给定列表中是否有 18 岁以上的用户。如果没有超过 18 岁的用户,则该方法应返回 -1。否则,它应该返回最年轻用户的年龄。
在使用流时,我创建了以下方法,但是,流被使用了两次。有没有更好的方法来使用流来做到这一点
public int test(List<User> userList) {
List<User> usersOver18 = userList.stream()
.filter(emp -> emp.getAge() > 18)
.collect(Collectors.toList());
if (usersOver18.isEmpty()) {
return -1;
}
return usersOver18.stream()
.min(Comparator.comparing(User::getAge))
.get().getAge();
}
Run Code Online (Sandbox Code Playgroud) 我对 IntStream 很新鲜,现在假设我有一个 Arraylist 保留了一些实体:
public ArrayList<Entity> entities(){return entities;}
ArrayList<Entity> entities=new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
然后我创建了一个具有 x、y 和半径作为字段的子类岩石:
record Rock(int x,int y,int radius) implements Entity{
//Some method
}
Run Code Online (Sandbox Code Playgroud)
现在我想返回半径从大到小排列的岩石:
OptionalInt findRock(ArrayList<Entity> es){
//This one returns the rock in a stored order, but I want get the rock sequence from big radius to small radius
return IntStream.range(0,es.size()).filter(i->es.get(i) instanceof Rock).findFirst();
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我有rock1 which radius == 15, rock2 which radius == 10, rock3 which radius == 20,它将返回rock3 -> rock1 -> rock2 …
我只是第一次看到这个,我想知道这是一个很好的做法还是一如既往地视情况而定。
使用流作为域中的属性而不是列表。
public class MyDomain {
Integer id;
Stream<SubDomain> subDomains;
}
Run Code Online (Sandbox Code Playgroud) 我想从一个列表中排除对象,其中 id 包含在另一个 Id 列表中,并获得一个字段名称字符串。" Care, Safe"
例子:
public interface Selectable {
Long getId();
String getName();
}
Run Code Online (Sandbox Code Playgroud)
我有一个 list<Selectable> tenants
id, name
34, "House"
35, "Care"
36, "Villa"
37, "Safe"
Run Code Online (Sandbox Code Playgroud)
而另一个 List<Long> idTenantsWithAlerts
id
34
36
Run Code Online (Sandbox Code Playgroud)
我需要的结果String tenantsNoAlerts是"Care, Safe"
我对 java8 流没有太多经验,所以我尝试了相同的过滤器、映射和减少......但没有运气。
我有一个带有字符串的列表并将相同的字符串分组。
List<String> allTypes = new ArrayList<String>();
Map<String, Long> count = allTypes.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)
然后我得到最频繁的字符串的计数
Long max = Collections.max(count.values());
Run Code Online (Sandbox Code Playgroud)
现在我不想要最频繁的字符串的计数,我也想要关联的字符串。该列表随机填充了来自其他列表的字符串。
我有文件 abbreviations.txt,其中包含特殊信息:
示例 abbreviations.txt :
PCAP_Personal Computer_Apple
NBHP_NoteBook_Hewlett Packard
TVSG_Televisor_Samsung
Run Code Online (Sandbox Code Playgroud)
我需要将所有品牌名称放入新的列表字符串中。我正在尝试使用这个:
Stream<String> abbreviations = Files.lines(Paths.get("src/main/resources/raceData/abbreviations.txt"))
.flatMap(Pattern.compile("_")::splitAsStream);
List<String> dates = abbreviations.collect(Collectors.toList());
dates.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
但作为 List 我得到:
PCAP_Personal Computer
Apple
TVSG_Televisor
Samsung
NBHP_NoteBook
Hewlett Packard
Run Code Online (Sandbox Code Playgroud) 我不能找到一种方法,使用流API ,并有一个简短的条件除了像.distinct()调用的合计操作的“管道”。
下面的代码显示了我如何在有条件的 .distinct() 调用之后复制 .filter 调用,使代码比我想要的更冗长:
AtomicInteger index = new AtomicInteger();
Supplier<Stream<NodeXType>> nodexSupplier = () -> myXMLPayload.getNodeXs().stream();
// Avoid BUG where the NodeXs are duplicated in the Payload XML impacting tests.
if (NODE_X.length < nodexSupplier.get().filter(e -> e.getSubTypeofNode_X().equalsIgnoreCase("myTargetValue")).count()){
LOGGER.log(Level.WARNING, "had more sub-type values than expected, so removed duplicates");
nodexSupplier.get()
.distinct()
.filter(e -> e.getSubTypeofNode_X().equalsIgnoreCase("myTargetValue"))
.forEachOrdered(e -> {
assertEquals(" myTargetValue nodes not updated to expected value",
e.getSubTypeofNode_X().getNewValue().toString(), NODE_X[index.getAndIncrement()]);
});
} else {
nodexSupplier.get()
.filter(e -> e.getSubTypeofNode_X().equalsIgnoreCase("myTargetValue"))
.forEachOrdered(e -> {
assertEquals(" myTargetValue …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 java 流 API 将两个二维数组的元素相互添加。
我用一维数组解决了这个问题,但我不知道如何进一步处理二维数组。
这是要转换的代码:
public static int[][] add(final int[][] m1, final int[][] m2) {
int[][] e = new int[m2.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m1[i].length; j++) {
e[i][j] = m1[i][j] + m2[i][j];
}
}
return e;
}
Run Code Online (Sandbox Code Playgroud)
这是我为相同目的编写的代码,但仅使用一维数组:
public static int[] addOneDimension(final int[] a, final int b[]) {
int[] c = IntStream.range(0, a.length)
.map(i -> a[i] + b[i])
.toArray(); …Run Code Online (Sandbox Code Playgroud) 为了代码可读性,我正在创建自定义函数接口,同时将其作为映射器传递给map(...),编译错误即将到来。需要帮忙。下面的例子简化了这个问题。例如
@FunctionalInterface
public interface Try<K,T> {
public K apply(T t);
}
public class Concrete{
//example
public static String checkFunc(Integer integer) {
return "Vivek";
}
}
public class CustomTest {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1,2,3);
Try<String,Integer> try1 = Concrete::checkFunc;
integers.parallelStream().map(try1); // compile error
//The method map(Function<? super Integer,? extends R>) in the type Stream<Integer> is not
//applicable for the arguments (Try<String,Integer>)
integers.parallelStream().map(Concrete::checkFunc); // this is perfectly fine
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试传递类似上面的映射器。如何正确地做到这一点?
java ×10
java-stream ×10
java-8 ×2
list ×2
arrays ×1
collections ×1
dictionary ×1
filter ×1
hashmap ×1
lambda ×1
optional ×1
reduce ×1
string ×1