Ultimately, I need to make an array of bytes from a string. How to make it beautiful? After all, the usual cast, if in a loop, it would be b [i] = (char) ch [i], but I want to understand with this example how the streams work. So far I could only make an array of ints, it will pass, but so an extra extension was added and then there will be a narrowing.

final int[] ints = str.chars().map(operand -> (byte) operand).toArray(); 

I have a string in ascii, so 256 characters is enough.

  • 2
    Why is str.getBytes() not suitable for str.getBytes() ? - Nofate
  • Stream API is a cool thing that is not intended to replace all of the operations on working with collections. It is often easier, faster and better to do everything with alternative methods. - etki
  • 2
    Friends will be boring, but the person wrote that he was just training and he wanted to try a new api for himself, albeit on non-optimal and stupid tasks. - Artem Konovalov
  • @Nofate, I did not know about this feature. Very convenient and solves my specific problem. It would be the answer, I would mark it as a solution. But I will leave the question as an example of bringing elements of an array through a stream. PS: I do not understand how the treatment for the nickname works, I set the dog, I copied the nickname, but it is not displayed as a link. - Eugene
  • @Eugene he should not become a link. Mentions through the dog in the comments fall in the notification of the mentioned participant. - Nofate

2 answers 2

You can't make char with streams. In java streams are only for primitive types: int, long and double. It is possible to achieve obtaining a Character array, but this, as you understand, will not be an array of primitives:

 Character[] array = "hello world".chars().mapToObj(s -> (char) s).toArray(Character[]::new); 
      String str = " qadadsadsa"; int[] ints = str.chars().toArray(); // есть легкий способ System.out.println(ints); // байты // по другим вопросам ArrayList<String> list = new ArrayList<String>(){{ this.add("5"); this.add("5"); this.add("4"); this.add("8"); this.add("9"); this.add("1"); this.add("6"); }}; List<String> strings = list .stream() .filter(f -> f.equals("5")) // все, что равно 5 .collect(Collectors.toList()); // собрать результат в list ArrayList<M> list2 = new ArrayList<M>(){{ this.add(new M(1,1)); this.add(new M(2,2)); this.add(new M(3,3)); this.add(new M(4,4)); this.add(new M(5,5)); this.add(new M(6,6)); this.add(new M(7,7)); }}; List<M> res = list2.stream() .filter(f -> fb > 3) // только те результаты, где b > 3 .limit(2) // ограничить до двух элементов (первые 2) .collect(Collectors.toList()); // собрать результат в list List<Integer> collect = res .stream() .map(m -> ma) // брать только значения а .collect(Collectors.toList()); // собрать результат в list public class M { public int a, b; public M(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "M{" + "a=" + a + ", b=" + b + '}'; } }