Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

Reassign all ints with a specific value in 2d array Java

Supppose I have a 2d array, grid defined like so:

    int[][] x = new int[][]{{0,0,1},{0,0,2},{0,0,3}};

Now suppose I want to reassign all positions in the grid with value 0 to Integer.MAX_VALUE

I can do this in Java 10:

        for(var row : grid) 
            for(int i=0; i<row.length; i++) 
                if(row[i] ==0) row[i]=Integer.MAX_VALUE;

Is there a way I can make this shorter without creating a new array? I know I can use streams, but won't that create a new array, wasting memory?

question from:https://stackoverflow.com/questions/65879518/reassign-all-ints-with-a-specific-value-in-2d-array-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just took a look at the Java 10 docs Arrays class to see what it might have to offer.

for(var row : arrayOfArrays)
    Arrays.setAll(row, i -> row[i] == 0 ? Integer.MAX_VALUE : row[i]);

Would only be helpful for removing one line, and is only applicable to inner loop.

Note that List<E> has a forEach(Consumer<E>) method (implemented from Iterable<E>) so you would be able to use forEach for the outer loop. However I was incorrect when I said you could try List<List<int>> because you would not be able to set the variable using the consumer variable. You could still do List<int[]> and then try the following.

List<int[]> listOfArrays = new ArrayList<>();
//Fill in values
listOfArrays.forEach(inner -> Arrays.setAll(inner, i -> inner[i] == 0 ? Integer.MAX_VALUE : inner[i]));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...