Java Stream: How to change only first element of stream?

Viewed 1190

There is an ArrayList:

 public void mainMethod() {
     List<String> list = new ArrayList<>();
     list.add("'+7913152','2020-05-25 00:00:25'");
     list.add("'8912345','2020-05-25 00:01:49'");
     list.add("'916952','2020-05-25 00:01:55'");
 }

and method which transforms a string:

 public String doTransform(String phone) {
     String correctNumber;
 ..... make some changes...
     return correctNumber;
 }


list.stream().forEach(line -> {
                Arrays.stream(line.split(","))... and what else? 

How to take only first element of sub-stream (Arrays.stream) and pass it to transforming method? "doTransform()" method is implemented, so don't care about it. I just need to separate '+7913152', '8912345' and '916952', pass it to doTransform() and get an new List:

"'8913152','2020-05-25 00:00:25'"
"'8912345','2020-05-25 00:01:49'"
"'8916952','2020-05-25 00:01:55'" 
4 Answers

Do it as follows:

List<String> result = list.stream()
                            .map(s -> {
                                    String[] parts = s.split(",");
                                    String st = doTransform(String.valueOf(Integer.parseInt(parts[0].replace("'", ""))));
                                    return ("'" + st + "'") + "," + parts[1];
                                }).collect(Collectors.toList());

Demo:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("'+7913152','2020-05-25 00:00:25'");
        list.add("'8912345','2020-05-25 00:01:49'");
        list.add("'916952','2020-05-25 00:01:55'");

        List<String> result = list.stream()
                                    .map(s -> {
                                        String[] parts = s.split(",");
                                        String st = doTransform(String.valueOf(Integer.parseInt(parts[0].replace("'", ""))));
                                        return ("'" + st + "'") + "," + parts[1];
                                    }).collect(Collectors.toList());

        // Display
        result.forEach(System.out::println);
    }

    static String doTransform(String phone) {
        return "x" + phone;
    }
}

Output:

'x7913152','2020-05-25 00:00:25'
'x8912345','2020-05-25 00:01:49'
'x916952','2020-05-25 00:01:55'

We can split elements using , in only two parts (initial which need to be change and remaining String) using limit on split String split.

List<String> list = list.stream()
  .map(input -> input.split(",", 2))
  .map(data -> String.join(",", doTransaform(data[0]), data[1]))
  .collect(Collectors.toList());

It can be helpful when your string has multiple commas (,) separated parts and will surely improve efficiency too.

I am assuming that length of the phone no in string as e.g "'+7913152','2020-05-25 00:00:25'" will be 7 if it's more than that you are going the remove the rest numbers from the head and replace with 8 to make it valid number else if number length is less than 7 then you will simply append the 8, Note: you can handle if the length of the number is like 3 or 4 etc.

 public class PlayWithStream {
        public static void main(String[] args) {
             List<String> list = new ArrayList<>();
                list.add("'+7913152','2020-05-25 00:00:25'");
                list.add("'8912345','2020-05-25 00:01:49'");
                list.add("'916952','2020-05-25 00:01:55'");
      List<String> collect = list.stream()
                    .map(PlayWithStream::doTransform)
                    .collect(Collectors.toList());

        System.out.println(collect);
        }
         public static String doTransform(String phone1) {
             String []a=phone1.split(",");
             String phone=a[0];

                 boolean flag2 = phone.substring(0, 1).matches("[8]");
                 String finaloutput="";
                 if(!flag2) {
                int len=phone.length();

                if(len>7) {
                    String sub=phone.substring(0,phone.length()-6);
                    String newStr=phone.replace(sub, "");
                    finaloutput="8".concat(newStr);

                }else {
                    finaloutput="8".concat(phone);
                }

            }
            return finaloutput+","+a[1];
         }
    }

The below code works,


List<String> collect = list.stream()
                .map(a -> a.replace(String.valueOf(a.charAt(1)), "2"))
                .collect(Collectors.toList());

Related