英文:
Dedupe array on basis of two things
问题
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
public class Dedupe {
public static class Pro {
String name;
Long firstPresent;
public Pro(String name, Long firstPresent) {
this.name = name;
this.firstPresent = firstPresent;
}
}
public static void main(String[] args) throws Exception {
List<Pro> pros = new ArrayList<>();
pros.add(new Pro("John", (long) 3));
pros.add(new Pro("Umar", (long) 1));
pros.add(new Pro("John", (long) 2));
pros.add(new Pro("John", (long) 0));
Map<String, Long> prosMap = new HashMap<>();
for (Pro pro : pros) {
String name = pro.name;
Long firstPresent = pro.firstPresent;
Long data = prosMap.getOrDefault(name, Long.MAX_VALUE);
if (data > firstPresent) {
prosMap.put(name, firstPresent);
}
}
List<Pro> result = new ArrayList<>();
for (Map.Entry<String, Long> entry : prosMap.entrySet()) {
result.add(new Pro(entry.getKey(), entry.getValue()));
}
// 'result' now contains the desired deduplicated array
}
}
英文:
import java.util.ArrayList;
import java.util.List;
public class Dedupe {
public static class Pro {
String name;
Long firstPresent;
public RouteHijack(String name, Long firstPresent, String matchedPrefix) {
this.name = name;
this.firstPresent = firstPresent;
}
}
public static void main(String[] args) throws Exception {
List<Pro> pros = new ArrayList<>();
pros.add(new Pro("John", (long) 3));
pros.add(new Pro("Umar", (long) 1));
pros.add(new Pro("John", (long) 2));
pros.add(new Pro("John", (long) 0));
}
}
Hi,
I want to dedupe the above array on basis of [name + Smallest value of firstPresent]. The desired resultant arry should contain
[Pro<"John", 0>, <"Umar", 1>]
I am looking forward some simpler way using language feature like stream or something similar. Do you know any simple way to achieve this in java8? Thanks for the help.
p.s: One solution is as below
Map<String, String> prosMap = new HashMap<>();
for (Pro pro : pros) {
String name = pro.getName();
Long firstPresent = pro.getFirstPresent();
String data = prosMap.getOrDefault(name, 0);
if (data < firstPresent) {
prosMap.put(name, firstPresent);
}
}
// Change the Map to array.
答案1
得分: 1
在Java 8的流API中有一个很棒的toMap
收集器:
pros.stream().collect(Collectors.toMap(pro -> pro.name, pro -> pro,
(a, b) -> a.firstPresent > b.firstPresent ? b : a
))
第三个参数是一个BinaryOperator
合并函数,它接受两个Pro
对象,然后仅返回其中一个。
在收集到映射之后,你可以简单地调用values()
来获取Collection<Pro>
。
英文:
There is a wonderful toMap
collector in Java 8 stream API:
pros.stream().collect(Collectors.toMap(pro -> pro.name, pro -> pro,
(a, b) -> a.firstPresent > b.firstPresent ? b : a
))
The third argument is a BinaryOperator
merge function that takes two Pro
objects and returns only one of them.
After collecting to a map you can simply call values()
to get Collection<Pro>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论