[英]how to get the intersection of a list of lists in Java using asynchronous and using multi-thread
我有一個這樣的Person
類:
public class Person {
public String name;
public List<String> hobbies;
public Person(String name, List<String> hobbies) {
this.name = name;
this.hobbies = hobbies;
}
//setter and getter
}
現在假設我有一個Person
對象列表,我想異步獲取愛好的交集。 我知道如何正常獲取兩個列表的交集,但我想以異步和多線程方式執行此操作。 一世
你可以這樣做:
List<Person> persons = new ArrayList<>();
persons.add(new Person("hatef", Arrays.asList("a", "b", "c", "t")));
persons.add(new Person("hatef", Arrays.asList("a", "b", "t")));
persons.add(new Person("hatef", Arrays.asList("t", "a", "b")));
persons.add(new Person("hatef", Arrays.asList("a", "b", "f", "t")));
persons.add(new Person("hatef", Arrays.asList("a", "t", "b", "z")));
然后使用CompletableFuture
Map<String, Integer> all = new ConcurrentHashMap<>();
ExecutorService executorService = Executors.newFixedThreadPool(Math.max(10, persons.size()));
persons
.stream()
.map(person -> CompletableFuture.supplyAsync(() -> person, executorService))
.map(p -> p.thenApply(Person::getHobbies))
.map(p -> p.thenAccept(hobbies -> hobbies.forEach(hobby -> all.compute(hobby, (key, value) -> value == null ? 1 : ++value))))
.map(CompletableFuture::join)
.forEach(x -> {}); // just dummy consumer to make stream triggers
int n = persons.size();
Set<String> result = all
.entrySet()
.stream()
.filter(entry -> entry.getValue() == n)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println(result);
這導致:
[a, b, t]
如果您在愛好列表中有訂單,我認為您可以使用最長公共前綴問題的想法並且它是有效的
我同意@JoachimSauer 的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.