Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

java - How to merge two corresponding values of two different variables in arraylist?

I want to merge two corresponding values of two different variables with comma separator in a row :

like Plate Numbers(Output) : MH 35353, AP 35989, NA 24455, DL 95405.

There is two different variables one is plate State and another is plate Number, I want to merge them together with their corresponding values like 1st values of plate State with 1st value of plate Number after that comma then so on..

I tried this code snippet but didn't work :

ArrayList<String> 
        list1 = new ArrayList<String>(); 

        list1.add("MH"); 
        list1.add("AP");
        list1.add("NA ");  
        list1.add("DL"); 

ArrayList<String> 
        list2 = new ArrayList<String>(); 

        list2.add("35353"); 
        list2.add("35989");
        list2.add("24455");
        list2.add("95405");

list1.addAll(list2); 
question from:https://stackoverflow.com/questions/65915973/how-to-merge-two-corresponding-values-of-two-different-variables-in-arraylist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use this :

 ArrayList<String> 
            list1 = new ArrayList<String>(); 
    
            list1.add("MH"); 
            list1.add("AP");
            list1.add("NA ");  
            list1.add("DL"); 
    
    ArrayList<String> 
            list2 = new ArrayList<String>(); 
    
            list2.add("35353"); 
            list2.add("35989");
            list2.add("24455");
            list2.add("95405");
    
     Iterator iterable = list2.iterator();
            List<String> list3 =list1.stream()
                 .map(x->{
                    x= x+" "+((String) iterable.next());
                    return x;})
                 .collect(Collectors.toList());

     String output = String.join(", ", list3);
                   System.out.println(output);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...