0

I have a String which I turn into an int stream of the ASCI numbers of the char values of each char of the String and then map it back to a String and also print out every char.

All of this works but I have a weird interaction with the .distinct() function that I don't quite understand.

It works just fine for my printer(c) function and the Output is:

hello d
hello c
hello b
hello a 

so it doesn't print the second b but if I print out a itself after the String still has the 2nd b.

What is the reason for that interaction?

public class MapTesting { public static void main(String [] args) {

      String a = "dcbba";
      a.chars().distinct().mapToObj( c -> (char) c).forEach(c -> MapTesting.printer(c));
      
      System.out.println(a);
      
  }
  public static void printer(Character c) {
      System.out.println("hello " + c);
  }

      }
44ly
  • 5
  • 3
  • Did you expect your function to modify the string in `a`? – that other guy Aug 11 '21 at 21:14
  • Can you please provide a complete example, including all code, input and output (as well as expected output), so we can see what is going on? – marstran Aug 11 '21 at 21:14
  • @thatotherguy yes that's more or less my question but I assume it just doesn't? Is there a different Method for that or would you have to use something like a StringBuilder? – 44ly Aug 11 '21 at 21:21
  • @marstran public class MapTesting { public static void main(String [] args) { String a = "dcbba"; a.chars().distinct().mapToObj( c -> (char) c).forEach(c -> MapTesting.printer(c)); System.out.println(a); } public static void printer(Character c) { System.out.println("hello " + c); } } – 44ly Aug 11 '21 at 21:22
  • Just edit the question – marstran Aug 11 '21 at 21:22

1 Answers1

0

Stream objects don't modify the original collection/object, they act on a copy. But more importantly, Strings are always immutable, so a will have all the contents you've defined it with, yes.

distinct() creates a Set behind the scene, but is not really related to the question you seem to be asking

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I was just wondering why distinct() influences the forEach part and not the String itself. S distinct() just can't influence the String itself, correct? – 44ly Aug 11 '21 at 21:17
  • You can think of the IntStream is added into a `Set`, one element at a time, thereby removing duplicates, then the `set.stream()` gets returned – OneCricketeer Aug 11 '21 at 21:52