Java 8 – Filter a string-X from a list using startsWith and Save the String-X to a list

  • A+

I am new to Java 8 and trying to get my head around how streams and filter works with list. I have a list of predefined strings and I have a string value which I am processing. I want to add the processed string to a new list if the string starts with any of the strings in the predefined list. If the string doesn't match any strings from the list then save it to another list.

For example:

List<String> internalIpAddresses= new ArrayList<>(); List<String> externalIpAddresses = new ArrayList<>();  List<String> ipAddresseses = new ArrayList<String>(); ipAddresses.add("10."); ipAddresses.add("132.174."); ipAddresses.add("192.168.");  // filter internal ip addresses for(String ipAddress : ipAddresseses){       if("".startsWith(ipAddress)) {           internalIpAddresses.add("");      } }  // filter external ip addresses for(String ipAddress : ipAddresseses){       if(!"".startsWith(ipAddress)) {           externalIpAddresses .add("");      } } 


internalIpAddresses: externalIpAddresses :  

Is there a way this can be achieved in a simpler way using stream in java 8?

Like:      .filter(ipAddress -> clientIpAddress.startsWith(ipAddress)      .*if the clientIpAddress starts with any of the values in the list then add to internalIpAddresses List      .*if clientIpAddress doesn't start with any values in list then add to externalIpAddresses List 

In the end I want to save the clientIpAddress ("" or ""), not the values from the ipAddresses ("10." or "192.168.") list.


Simply, your iterative code using streams could be represented as :

List<String> ipAddresses = Arrays.asList("10.", "132.174.", "192.168.");  List<String> internalIpAddresses =         .filter(""::startsWith)         .map(ipAddress -> "")         .collect(Collectors.toList());  List<String> externalIpAddresses =         .filter(ipAddress -> !"".startsWith(ipAddress)) // I doubt this should be '.filter(""::startsWith)'         .map(ipAddress -> "")         .collect(Collectors.toList()); 

A general approach as suggested in comments for solving this could be using:

List<String> internalIpAddresses = Stream.of("") // can add more addresses         .filter(ip ->         .collect(Collectors.toList()); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: