Merge the two lists into a “two-dimensional” list in Java

See English answers > clearest way to combine two lists into a map (Java)? 15 @ h_ 502_ 7@ I have two lists:

Names= ["John","Mark","Jo","Peter"];
Values= [1.1,1.2,1.3,1.4];

I want to merge them into:

info=[["John",1.1],["Mark",1.2],["Jo",1.3],["Peter",1.4]];

How can I do this? Can I help you

resolvent

Solution

Ideally, in this case, you need to create a class with two field names, then rotate many of the required objects with the specified names and values and store them in the list, making life easier to maintain relevant data and perform further operations on the objects later

Another solution is to use the map suggested by another answer, provided there are no duplicate names

However, if you do not want to continue with the suggested method, you can combine the two lists:

Starting with java-8:

List<List<Object>> merged = 
      IntStream.range(0,Names.size())
               .mapToObj(i -> Arrays.asList((Object) Names.get(i),Values.get(i)))
               .collect(Collectors.toList());

Or urgent method:

List<List<Object>> merged = new ArrayList<>();    
for (int i = 0; i < Names.size(); i++) {
      List<Object> temp = new ArrayList<>();
      temp.add(Names.get(i));
      temp.add(Values.get(i));
      merged.add(temp);
}

Note that with the imperative method, you can modify the nested list after merging, while in the first case, you cannot modify the nested list I'll leave it to you when deciding which situation is best for you

By the way, you should start variables with lowercase letters, that is, names instead of names and values instead of values

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>