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

You can try :

ipAddresseses.stream()
 .collect(Collectors.partitioningBy(ipAddress -> ipAddress.startsWith("10.11.12.13")));

This will give a Map with two elements, one with good ipAddress and one with bad.


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

List<String> ipAddresses = Arrays.asList("10.", "132.174.", "192.168.");

List<String> internalIpAddresses = ipAddresses.stream()
        .filter("10.11.12.13"::startsWith)
        .map(ipAddress -> "10.11.12.13")
        .collect(Collectors.toList());

List<String> externalIpAddresses = ipAddresses.stream()
        .filter(ipAddress -> !"5.6.7.8".startsWith(ipAddress)) // I doubt this should be '.filter("5.6.7.8"::startsWith)'
        .map(ipAddress -> "5.6.7.8")
        .collect(Collectors.toList());

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

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

You can do this -

  ipAddresseses.stream().foreach( ipaddress 
 -> decideGoodOrBadAndAdd(s);

Create one method which will check if it's good or bad ip address and add it in respective list accordingly-

  public void decideGoodOrBadAndAdd(String 
  ipaddress){

  if("10.11.12.13".startsWith(ipAddress)) {
        goodIpAddresses.add(ipAddress);
   }
  else if(!"5.6.7.8".startsWith(ipAddress)) {
        badIpAddresses.add(ipAddress);
   }
}