简体   繁体   English

从两个具有相同键和值的列表创建对象

[英]Create map from two lists with key and value as same object

I have 2 lists which contain Objects. 我有2个包含对象的列表。 These 2 lists can have same Objects in different order. 这两个列表可以具有不同顺序的相同对象。

I have overridden the equals method in the Object such that if one particular property of the object is same as other Object then they are equal even if other properties are not same. 我重写了Object中的equals方法,这样,如果该对象的一个​​特定属性与其他Object相同,那么即使其他属性不相同,它们也相等。

Now I need to create a map where the key is the Object from one list and value is the same Object from the other list. 现在,我需要创建一个映射,其中键是一个列表中的Object,值是另一个列表中的相同Object。 If there is an Object in one list which does not have an equal object in the other list, those Objects should be ignored while creating the Map. 如果一个列表中有一个对象,而另一个列表中没有相同的对象,则在创建Map时应忽略这些对象。

How can i accomplish this using java stream? 我如何使用Java流完成此操作?

I can see why you want to do something like this, but it seems very hacky. 我可以看到您为什么要执行这样的操作,但是看起来很不客气。 I'm sure if you tell us what you're trying to achieve, we can provide you with a better design. 我敢肯定,如果您告诉我们您要达到的目标,我们可以为您提供更好的设计。 Regardless, the following will work with Java 10: 无论如何,以下将适用于Java 10:

var list1 = List.of("One", "Two", "Three");
var list2 = List.of("Two", "Three", "Four");

var set = Set.copyOf(list2);

var map = list1.stream()
               .filter(set::contains)
               .collect(Collectors.toMap(k -> k, v -> list2.get(list2.indexOf(v))));

System.out.println(map);

Output: 输出:

{Two=Two, Three=Three}

The equivalent code written for Java 8 is as follows: 为Java 8编写的等效代码如下:

List<String> list1 = Arrays.asList("One", "Two", "Three");
List<String> list2 = Arrays.asList("Two", "Three", "Four");

Set<String> set = new HashSet<>(list2);

// Defined the Map here for formatting reasons.
Map<String, String> map;

map = list1.stream()
           .filter(set::contains)
           .collect(Collectors.toMap(k -> k, v -> list2.get(list2.indexOf(v))));

System.out.println(map);

Note : This assumes that you have overridden Object#hashCode as well as Object#equals . 注意 :假设您已覆盖Object#hashCodeObject#equals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM